#!/usr/bin/perl
use warnings;
use strict;
use Tk;
use Tk::Trace;
use Tk::LabFrame;
use Tk::ProgressBar;
use Tk::NoteBook;

use Tk::Dialog;

use Tk;
use utf8;
use constant PI => 3.1415926;

use DBI;
use File::HomeDir;
use Config::Simple;
use Tk::Chart;
use Tk::Chart::Lines;
use Tk::Canvas::GradientColor;
use Tk::PNG;

use Number::Bytes::Human qw(format_bytes);

use Scalar::Util qw(looks_like_number);

my ($configuration_file, $homedir, $dbfile, $lang) = homedir();
$lang = 'ru_RU.UTF-8' if (!$lang);
my $databasedir;
my $os = $^O;
my $PortObj;
my ($connbutt, $connbutt2);

my $x0 = 15; #was 15
my $y0 = 80; #was 50
my $x_max = 640;
my $y_max = 570;

my $font_global_set =1;

my $screen;

my $testcount; #for shutdown ups func

my $map_operation;
my %param;
my $port_in_use = '/dev/ttyUSB0';
my $port_not_opening ="";
my $serial_connection;
my %readings;
my $reading;
my $debug = 0;
my ($map_power, $qty, $map_current_max);
#$qty=4;
my ($coords_xy, $status, $status_batt_type, $status_batt_cap, $voltage_acc, $voltage_socket_out, $Cacc, $Cacc_text); #vars from map
my ($disconnected, $temp_batt_text, $temp_batt, $status_freq_text, $status_volt_in_text); #vars from map
my ($acc_status, $status_batt_map_text, $acc_discharged);
my ($temp_transistors_text, $temp_tor_text, $map_params_text);
my ($signal_form); #eeprom addr to read/write to
my ($powermeter, $power_text);
my ($signal_form_set, $acc_type, $charge_alg, $net_control_alg, $sound_control, $lcd_backlight, $acc_consrv); #map_settings
my $conn_speed = 19200;
my $conn_try_count=0;
my ($tbd, $settings, $font_counter, $t);
my ($times, $times2, $time_hours_map, $time_minutes_map, $real_time_label);
my ($time_savings_begin_label, $time_savings_begin_hours, $time_savings_begin_minutes);
my ($time_savings_end_label, $time_savings_end_hours, $time_savings_end_minutes);
my ($map_voltage_generated, $map_net_level_lower, $map_net_level_upper, $map_min_extra_gen_level, $map_voltage_acc_gen_end);
my ($map_acc_charge_start, $map_acc_sust_charge, $map_acc_charge_end );
my ($load_start, $current_end_charge, $current_start_charge, $capacity_entire);
my ($map_versions, $map_versions_changes);
my ($net_type_label, $map_max_charge_time);
my $read_counter = 0;
my $timestamp;
my ($prompt_warning, $warnings);
my ($prompt_errors, $errors);
my ($prompt_errors_version, $errors_version);
my ($errors_JobM, $prompt_errors_JobM, $errors_ErrJob, $prompt_errors_ErrJob);
my $load_start_entry;
my ($database_path_text, $homedirtext, $databasepath);
my ($buttonchoice, $connbutt_text, $connbutt_text1, $connbutt_text2, $connbutt_text3);
my $count_shutdown;

my @voltage_acc_charge_end = ('-','11.5','11.7', '11.8', '12', '12.1', '12.3', '12.4', '12.5', '12.6', '12.7', '12.6','13.7','13.8','13.9','14.0','14.1','14.2','14.3','14.4','14.5','14.6','14.7', '14.8','14.9','15','15.1');
my @voltage_acc_sust_charge = ('-','13.0','13.1','13.2','13.3','13.4','13.5','13.6','13.7','13.8','13.9','14.0', '14.1','14.2','14.3','14.4','14.5','14.6'.'14.7','14.8','14.9','15');
my @voltage_acc_charge_start = ('-','9.0','9.5','10.0','10.5','11.0','11.5','11.7', '11.8', '12', '12.1', '12.3', '12.4', '12.5', '12.6', '12.7', '12.6','13.7','13.8','13.9','14.0','14.1','14.2','14.3','14.4','14.5','14.6','14.7', '14.8','14.9','15','15.1'); 
my @voltage_acc_gen_end = ('-','9.0','9.5','10.0','10.5','11.0','11.5','11.7', '11.8', '12', '12.1', '12.3', '12.4', '12.5', '12.6', '12.7', '12.6','13.7','13.8','13.9','14.0','14.1','14.2','14.3','14.4','14.5','14.6','14.7', '14.8','14.9','15','15.1');
my @voltage_min_extra_gen_level = ('-','8.5','9','9.5','10','10.5','11','11.5','11.7', '11.8', '12', '12.1', '12.3', '12.4', '12.5', '12.6', '12.7', '12.6','13.7','13.8','13.9','14.0','14.1','14.2','14.3','14.4','14.5','14.6','14.7', '14.8','14.9','15','15.1');


my @voltage_upper_level = ('-','210','215','220','225','230','235','240','245','250','255','260','265');
my @voltage_low_level = ('-','165','170','175','180','185','190','195','200','205','210','215','220');
my @voltage_generated = ('-','100','110','120','130','140','150','160','170','180','190','200','210','220','230','240');
my @hour_labels = ('-','00','01','02','03','04','05','06','07','08','09','10','11','12',
			'13','14','15','16','17','18','19','20', '21','22','23');
my @minute_labels = ('-','00','10','20','30','40','50');

#my $disp{$lang}{'МАП SIN "ЭНЕРГИЯ"'}
my %disp = (
	'ru_RU.UTF-8' => {
		'МАП SIN "ЭНЕРГИЯ"' => 'МАП SIN "ЭНЕРГИЯ"',
		'Режим: ' => 'Режим: ',
		'U вход.: ' => 'U вход.: ',
		'ОС:' => 'ОС:',
		'Установлено АКБ: ' => 'Установлено АКБ: ',
		'Тип АКБ: ' => 'Тип АКБ: ',
		'Частота U вых.: ' => 'Частота U вых.: ',
	},
	'en_US.UTF-8' => {
		'МАП SIN "ЭНЕРГИЯ"' => 'MAC "ENERGIA" SINE',
		'Режим: ' => 'Mode: ',
		'U вход.: ' => 'Vin grid: ',
		'ОС:' => 'OS:',
		'Установлено АКБ: ' => 'Batt. capacity: ',
		'Тип АКБ: ' => 'Batt. type:',
		'Частота U вых.: ' => 'Frequency Vout:',
	} 
);

my %EnErrSis = (
	1 => 'Не работает SPI', 2 => 'Ошибка записи в EEPROM', 4 => 'Кто-то другой вызвал интерапт',
	8 => 'Не работает датчик температуры', 0x10 => 'Друга системная ошибка', 0x20 => 'Несоответствие перемычек',
);

my %EnErrJobM = (
	1 => 'Асс полностью разряжен - мгновенное', 2 => 'Превышение напряжения на Acc',
	4 => 'Превышение напряжения на Acc во время заряда', 8 => 'Ток KZ по Acc',
	0x10 => 'Залипло основное реле, т.к. пропускает сеть (потому как выход равен входу) хотя не должна',
	0x20 => 'Ток КЗ по сети',
	0x40 => 'На выходе розетки постороннее напряжение либо залипло зарядное реле',
	0x80 => 'Произошел ресет',
);

my %EnErrJob = (
	1 => 'Асс полностью разряжен', 2 => 'Ток перегрузки', 4 => 'Номинальный ток - работаем огранниченное время',
	8 => 'Превышение температуры', 0x10 => 'Кулер не крутится', 0x20 => 'Ток перегрузки по сети',
	0x40 => 'Был сбой в режиме работы (например по сбросу питания или сильной помехи)',
);

my %EnWarning = (
	1 => 'Нет действия для комбинации клавиш', 2 => 'Сетевое напряжение вышло за пределы',
	4 => 'Сеть на выходной розетке или большие выбросы от нагрузки',
	8 => 'Локальная потеря данных от SPI',
	0x10 => 'Залипла кнопка', 0x20 => 'Переход на заряд не возможен - нет сети',
	0x40 => 'Мощность нагрузки за пределами дизеля, но меньше мощности МАР',
);
my %EnStateUAcc = (
	'ru_RU.UTF-8' => {
        	0 => 'низкое',
        	1 => 'минимальное',
        	2 => 'среднее',
        	3 => 'нормальное',
        	4 => 'максимальное',
        	5 => 'превышено',
		'н/д' => 'нет данных',
	},
        'en_US.UTF-8' => {
		0 => 'low',
                1 => 'minimal',
                2 => 'average',
                3 => 'normal',
                4 => 'max',
                5 => 'overcharge',
                'н/д' => 'n/a',
        }
);

my %MapStatuses = (
	'ru_RU.UTF-8' => {
		0 => 'выключено без сети',
		1 => 'выключено с сетью',
		2 => 'питание от АКБ', #'включено без сети [работает МАП]',
		3 => 'включено с сетью',
		4 => 'включено с зарядом',
		5 => 'выключено при неоходимости подзаряд [сеть пропускает на выход]',
		33 => "Нет соединения с МАП-ом ($port_not_opening)",
        },
        'en_US.UTF-8' => {
		0 => 'Off w/o grid',
                1 => 'Off w/grid',
                2 => 'Battery powered', #'включено без сети [работает МАП]',
                3 => 'On w/grid',
                4 => 'On w/charge',
                5 => 'Off w/charge on demand [grid powered]',
                33 => "Lack of communication w/mac ($port_not_opening)",
        }

);

my %batt_types = (
	'ru_RU.UTF-8' => {
		'0' => 'Кислотный Рег', 
		1 => 'Гелевый/AGM T', 
		2 => 'Кислотный T', 
		3 => 'Щелочной', 
	},
	'en_US.UTF-8' => {
		'0' => 'Acid Reg', 
                1 => 'AGM T', 
                2 => 'Acid T', 
                3 => 'Alcaline',
	}
);

my $logcount=1;
my %log;
my %lastlog;
my @mapcommand =('P', 'C', 'R', 'D', '4', '0', '0', '6', 'C', "\r", "\n");

###############################################charting vars
my ($chart, $chart2, $chart3,  $mwc);
my @chart_periods;
if ($lang eq 'en_US.UTF-8'){
	@chart_periods =(['Charts' => '1'], ['24 hours'=>'2'],['week' => '3'],['month'=>'4'],['6 months'=>'5'],['entire'=>'6']);
} else {
	@chart_periods =(['График' => '1'], ['24 часа'=>'2'],['неделя' => '3'],['месяц'=>'4'],['6 мес'=>'5'],['все'=>'6']);
}
my ($chart_period_type, $font_counter_ch, $chart_exit);
my $chart_type = 'p';
my ($old_interval, $xlabelskip);
my ($zoom, $zoomsign);
my (@data, @data2, @data3);
my ($minid, $maxid);
########################################end of charting vars

my $mw = MainWindow->new;
#$mw->waitVariable(\$qty); 
#$mw->overrideredirect(1);
if ($lang eq 'en_US.UTF-8'){
	$mw -> title ('MAC monitoring & setup');
} else {
	$mw -> title ('Мониторинг и настройки МАП');
}

$mw->optionAdd("*font", "*utf-8");

my $ico = $mw->Photo(-data => &encoded_ico, -format => 'png');
$mw->Icon(-image => $ico);
#$mw->setIcon(-data => &encoded_ico);


if ($os =~ /Win/i){
        eval "use Win32::SerialPort; 1" or die $@;
} else {
        eval "use Device::SerialPort; 1" or die $@;
}
if ($font_global_set == 1){
	if ($os =~ /Win/i){
        	$mw->fontCreate('medium', -family=>'courier', -weight=>'bold', -size=>int(-14*14/10));
        	$mw->fontCreate('ticks', -family=>'courier', -weight=>'normal', -size=>int(-11*11/10));
        	$mw->fontCreate('dial_rus', -family => 'ariel', -weight => 'normal', -size=>int(-14*14/10));
        	$mw->fontCreate('logo_rus', -family => 'ariel', -weight => 'bold', -size=>int(-17.5*17.5/10));
        	$mw->fontCreate('giant_logo_rus', -family => 'ariel', -weight => 'bold', -size=>int(-17*17/10));
        	$mw->fontCreate('giant_logo_eng', -family => 'ariel', -weight => 'bold', -size=>int(-18*18/10));
        	#$mw->fontCreate('bar_rus', -family => 'ariel', -weight => 'normal', -size=>int(-11.5*11.5/10));
        	$mw->fontCreate('bar_rus', -family => 'ariel', -weight => 'normal', -size=>int(-12.0*12/10));
        	$mw->fontCreate('info_rus', -family => 'ariel', -weight => 'bold', -size=>int(-13*13/10));
	} else {
        	$mw->fontCreate('medium', -family=>'courier', -weight=>'bold', -size=>int(-14*14/10));
        	$mw->fontCreate('ticks', -family=>'courier', -weight=>'normal', -size=>int(-11*11/10));
        	$mw->fontCreate('dial_rus', -family => 'nimbus sans l', -weight => 'normal', -size=>int(-14*14/10));
        	$mw->fontCreate('logo_rus', -family => 'nimbus sans l', -weight => 'bold', -size=>int(-17.5*17.5/10));
        	$mw->fontCreate('giant_logo_rus', -family => 'nimbus sans l', -weight => 'bold', -size=>int(-17*17/10));
        	$mw->fontCreate('giant_logo_eng', -family => 'helvetica', -weight => 'bold', -size=>int(-18*18/10));
        	#$mw->fontCreate('bar_rus', -family => 'nimbus sans l', -weight => 'normal', -size=>int(-11.5*11.5/10));
        	$mw->fontCreate('bar_rus', -family => 'nimbus sans l', -weight => 'normal', -size=>int(-12*12/10));
        	$mw->fontCreate('info_rus', -family => 'nimbus sans l', -weight => 'bold', -size=>int(-13*13/10));
	}
}
$font_global_set = 2;

my $c = $mw->Canvas( -width => $x_max, -height => $y_max, -bd => 1,-relief => 'sunken', -background => '#0f134d', scrollregion=>[0,0,$x_max,$y_max],)->grid;
$mw->resizable(0,0);

my $coords_curs;

#my $text_logo_1 = $c->createText(15, 15,-text=>'МАП SIN "ЭНЕРГИЯ"', -font=>'giant_logo_rus', -fill=>'#afb3b0',-anchor=>'nw',-tags => ['logo']);

my $text_logo_1;
if ($lang eq 'en_US.UTF-8'){
	$text_logo_1 = $c->createText(15, 15,-text=>'MAC "ENERGIA" SINE', -font=>'giant_logo_rus', -fill=>'#afb3b0',-anchor=>'nw',-tags => ['logo_eng']);
} else {
	$text_logo_1 = $c->createText(15, 15,-text=>'МАП SIN "ЭНЕРГИЯ"', -font=>'giant_logo_rus', -fill=>'#afb3b0',-anchor=>'nw',-tags => ['logo_eng']);
}



#&connect unless ($disconnected);
#my $map_version = &readmap('6') unless ($port_not_opening); #power
#my %device_qty = ( '0' => '1','1'=>'2','2'=>'4');
#$qty = $device_qty{$map_version};


my $map_versions_text = $c->createText(15, 45, -text=>$map_versions_changes, -font=>'bar_rus', -fill=>'#afb3b0', -anchor=>'nw',-tags => ['logo_stats']);

my $map_params = $c->createText(350, 20,-text=> $map_params_text, -font=>'info_rus', -fill=>'#afb3b0',-anchor=>'nw',-tags => ['logo']);

my $text_os = $c->createText(348,95,-text=>"$disp{$lang}{'ОС:'} $os", -font=>'bar_rus', -fill=>'#afb3b0',-anchor=>'ne',-tags => ['os']);

my $status_map_sign = $c->createText(330, 15, -text => $disp{$lang}{'Режим: '} , -font=>'info_rus', -fill=>'#afb3b0',-anchor=>'nw',-tags => ['status_map']);
my $status_map = $c->createText(400, 15, -text => $status , -font=>'info_rus', -fill=>'#afb3b0',-anchor=>'nw',-tags => ['status_map']);

my $status_volt_in_sign = $c->createText(330, 35, -text => $disp{$lang}{'U вход.: '} , -font=>'info_rus', -fill=>'#afb3b0',-anchor=>'nw',-tags => ['volt_in']);
my $status_volt_in = $c->createText(400, 35, -text => $status_volt_in_text , -font=>'info_rus', -fill=>'#afb3b0',-anchor=>'nw',-tags => ['volt_in']);

my $gauge1 = $c->createImage(15, 85, -image => $mw->Photo(-data => &encoded_gif, -format => 'gif'), -anchor => 'nw', -tags => ['gauge1']); #gauge 300x173
my $gauge2 = $c->createImage(327, 85, -image => $mw->Photo(-data => &encoded_gif, -format => 'gif'), -anchor => 'nw', -tags => ['gauge2']); #gauge 2 

#needles
$c->createLine(166, 250, 166, 250, -tags => ['needle1'], -arrowshape => [ 6, 6, 0 ], -arrow => 'last', -width => 5, -fill => 'white',);
$c->createLine(475, 250, 475, 250, -tags => ['needle2'], -arrowshape => [ 6, 6, 0 ],-arrow => 'last', -width => 5, -fill => 'white',);

#gauge1 ticks V acc 12 v...9-15v

my ($x_shift, $y_shift);
#my $dial_0 = $c->createText( 56, 233, -text  => 9*$qty, -font  => 'ticks', -fill  => '#f1f3f0', -anchor => 'nw');
#my $dial_16 = $c->createText( 72, 180, -text  => 10*$qty, -font  => 'ticks', -fill  => '#f1f3f0', -anchor => 'nw');
#my $dial_33 = $c->createText( 111, 147, -text  => 11*$qty, -font  => 'ticks', -fill  => '#f1f3f0', -anchor => 'nw');
#my $dial_50 = $c->createText( 160, 134, -text  => 12*$qty, -font  => 'ticks', -fill  => '#f1f3f0', -anchor => 'nw');
#my $dial_66 = $c->createText( 210, 148, -text  => 13*$qty, -font  => 'ticks', -fill  => '#f1f3f0', -anchor => 'nw');
#my $dial_79 = $c->createText( 247, 181, -text  => 14*$qty, -font  => 'ticks', -fill  => '#f1f3f0', -anchor => 'nw');

#gauge2 ticks V ac out 190-250v
my $dial_2_0 = $c->createText( 368, 233, -text  => '190', -font  => 'ticks', -fill  => '#f1f3f0', -anchor => 'nw');
my $dial_2_16 = $c->createText( 386, 180, -text  => '200', -font  => 'ticks', -fill  => '#f1f3f0', -anchor => 'nw');
my $dial_2_33 = $c->createText( 426, 147, -text  => '210', -font  => 'ticks', -fill  => '#f1f3f0', -anchor => 'nw');
my $dial_2_50 = $c->createText( 468, 134, -text  => '220', -font  => 'ticks', -fill  => '#f1f3f0', -anchor => 'nw');
my $dial_2_66 = $c->createText( 522, 148, -text  => '230', -font  => 'ticks', -fill  => '#f1f3f0', -anchor => 'nw');
my $dial_2_79 = $c->createText( 555, 181, -text  => '240', -font  => 'ticks', -fill  => '#f1f3f0', -anchor => 'nw');

my ($dial_rus1, $dial_rus2);
if ($lang eq 'en_US.UTF-8'){
	$dial_rus1 = $c->createText( 215, 225, -text  => 'V Batt', -font  => 'dial_rus', -fill  => '#10f0f0', -anchor => 'nw'); #Vakb	
	$dial_rus2 = $c->createText( 520, 225, -text  => 'Vac out', -font  => 'dial_rus', -fill  => '#10f0f0', -anchor => 'nw');  #V	
} else {
	$dial_rus1 = $c->createText( 215, 225, -text  => 'U акб', -font  => 'dial_rus', -fill  => '#10f0f0', -anchor => 'nw'); #Vakb
	$dial_rus2 = $c->createText( 535, 225, -text  => 'U~', -font  => 'dial_rus', -fill  => '#10f0f0', -anchor => 'nw');  #V~
}

my $voltage_acc_text = $c->createText(65, 225, -text  => $voltage_acc, -font  => 'dial_rus',
	-fill  => '#10f0f0', -anchor => 'nw', -tags => ['text']);
my $voltage_socket_out_text = $c->createText( 395, 225, -text  => $voltage_socket_out, -font  => 'dial_rus',
	-fill  => '#10f0f0', -anchor => 'nw', -tags => ['text2']);

my $frame_batt = $mw->LabFrame( -background => '#0f134d', -foreground => '#10f0f0', -font => 'bar_rus', -labelside => 'acrosstop',
	-labelvariable => \$Cacc_text,  #Заголовок рамки
	-height => 27,         		#Высота рамки
        -width  => 295,  		#Ширина рамки
)->place( -x => 15, -y => 262);  	#Положение на странице программы 

my $progress_batt = $frame_batt->ProgressBar(
        -highlightbackground => '#0f134d', -highlightcolor => '#0f134d', -highlightthickness => 0, -borderwidth => 1, -relief => 'sunken',
	-length => 285, -width => 18, -padx => 1, -pady => 1,
	-variable => \$Cacc,
	-colors => [0 => 'orangered2', 30 => 'darkblue' , 70 => '#10f0f0'],
	-resolution => 1, -blocks => 12, -anchor => 'w',-from => 0, -to => 100,
)->place(-x => 5, -y => 7,);

my $status_batt_text_sign = $c->createText(335, 317, -text => $disp{$lang}{'Установлено АКБ: '} , -font=>'info_rus', -fill=>'#afb3b0',-anchor=>'nw');
my $status_batt_text = $c->createText(490, 317, -text => $status_batt_cap , -font=>'info_rus', -fill=>'#afb3b0',-anchor=>'nw');
my $status_batt_type_text_sign = $c->createText(335, 353, -text => $disp{$lang}{'Тип АКБ: '} , -font=>'info_rus', -fill=>'#afb3b0',-anchor=>'nw');
my $status_batt_type_text = $c->createText(420, 353, -text => $status_batt_type , -font=>'info_rus', -fill=>'#afb3b0',-anchor=>'nw');

my $frame_temp_batt = $mw->LabFrame( -background => '#0f134d', -foreground => '#10f0f0', -font => 'bar_rus', -labelside => 'acrosstop',
        -labelvariable => \$temp_batt_text,  #Заголовок рамки
        -height => 27,                  #Высота рамки
        -width  => 295,                 #Ширина рамки
)->place( -x => 15, -y => 328);         #Положение на странице программы 

my $progress_temp_batt = $frame_temp_batt->ProgressBar(
        -highlightbackground => '#0f134d', -highlightcolor => '#0f134d', -highlightthickness => 0, -borderwidth => 1, -relief => 'sunken',
        -length => 285, -width => 18, -padx => 1, -pady => 1,
        -variable => \$temp_batt,
        -colors => [ -50 => '#10f0f0', -10=> 'darkblue', 50 => 'orangered2'],
        -resolution => 1, -blocks => 12, -anchor => 'w',-from => -50, -to => 50,
)->place(-x => 5, -y => 7,);

my $frame_power = $mw->LabFrame( -background => '#0f134d', -foreground => '#10f0f0', -font => 'bar_rus', -labelside => 'acrosstop',
        -labelvariable => \$power_text,  #Заголовок рамки
        -height => 27,                  #Высота рамки
        -width  => 295,                 #Ширина рамки
)->place( -x => 327, -y => 262);         #Положение на странице программы
my $progress_power = $frame_power->ProgressBar(
        -highlightbackground => '#0f134d', -highlightcolor => '#0f134d', -highlightthickness => 0, -borderwidth => 1, -relief => 'sunken',
        -length => 285, -width => 18, -padx => 1, -pady => 1,
        -variable => \$powermeter,
        -colors => [ 0 => '#10f0f0', 50=> 'darkblue', 150 => 'orangered2'],
        -resolution => 1, -blocks => 12, -anchor => 'w',-from => 0, -to => 150,
)->place(-x => 5, -y => 7,);





my $temp_transistors;
if ($lang eq 'en_US.UTF-8'){
	$temp_transistors = $c->createText(20, 392, -text => 'Transistor temp.: ' , -font=>'bar_rus', -fill=>'#10f0f0',-anchor=>'nw',-tags => ['status_map']);
} else {
	$temp_transistors = $c->createText(20, 392, -text => 'Транзисторы: ' , -font=>'bar_rus', -fill=>'#10f0f0',-anchor=>'nw',-tags => ['status_map']);
}
my $temp_transistors_sign = $c->createText(140, 392, -text => $temp_transistors_text , -font=>'bar_rus', -fill=>'#10f0f0',-anchor=>'nw',-tags => ['status_map']);

my $temp_tor;
if ($lang eq 'en_US.UTF-8'){
	$temp_tor = $c->createText(175, 392, -text => 'Transformer: ' , -font=>'bar_rus', -fill=>'#10f0f0',-anchor=>'nw',-tags => ['status_map']);
} else {
	$temp_tor = $c->createText(175, 392, -text => 'Темп. тора: ' , -font=>'bar_rus', -fill=>'#10f0f0',-anchor=>'nw',-tags => ['status_map']);
}
my $temp_tor_sign = $c->createText(270, 392, -text => $temp_tor_text , -font=>'bar_rus', -fill=>'#10f0f0',-anchor=>'nw',-tags => ['status_map']);

my $status_freq_sign = $c->createText(335, 385, -text => $disp{$lang}{'Частота U вых.: '} , -font=>'info_rus', -fill=>'#afb3b0',-anchor=>'nw',-tags => ['status_map']);
my $status_freq = $c->createText(490, 385, -text => $status_freq_text , -font=>'info_rus', -fill=>'#afb3b0',-anchor=>'nw',-tags => ['status_map']);


my ($button1, $button2, $button3, $button4);
if ($lang eq 'en_US.UTF-8'){
	$button1 = $mw->Photo(-data => &encoded_but1eng, -format => 'gif');
        $button2 = $mw->Photo(-data => &encoded_but2eng, -format => 'gif');
        $button3 = $mw->Photo(-data => &encoded_but_exit1eng, -format => 'gif');
        $button4 = $mw->Photo(-data => &encoded_but_exit2eng, -format => 'gif');
} else {
	$button1 = $mw->Photo(-data => &encoded_but1, -format => 'gif');
	$button2 = $mw->Photo(-data => &encoded_but2, -format => 'gif');
	$button3 = $mw->Photo(-data => &encoded_but_exit1, -format => 'gif');
	$button4 = $mw->Photo(-data => &encoded_but_exit2, -format => 'gif');
}


my $but1 = $c->createImage(63, 415, -image => $button1, -anchor => 'nw', -tags => ['but1']);

$c->bind( $but1, '<Enter>', sub {$c->itemconfigure( $but1, -image => $button2); });
$c->bind( $but1, '<Leave>', sub {$c->itemconfigure( $but1, -image => $button1); });
$settings = "";
$c->bind( $but1, '<ButtonPress>', sub{ $settings=1; &tabbed; } );

my $but2 = $c->createImage(390, 415, -image => $button3, -anchor => 'nw', -tags => ['but2']);

$c->bind( $but2, '<Enter>', sub {$c->itemconfigure( $but2, -image => $button4); });
$c->bind( $but2, '<Leave>', sub {$c->itemconfigure( $but2, -image => $button3); });
$disconnected = "";
$c->bind( $but2, '<ButtonPress>', sub {
	$disconnected = 1; #exit from the main sub
	&disconnect; 
});




my $chartlogo1 = $mw->Photo(-data => &encoded_chartlogo1, -format => 'gif');
my $chartlogo2 = $mw->Photo(-data => &encoded_chartlogo2, -format => 'gif');

my $chartlogos = $c->createImage(588, 355, -image => $chartlogo1, -anchor => 'nw', -tags => ['chartlogos']);

$c->bind( $chartlogos, '<Enter>', sub {$c->itemconfigure( $chartlogos, -image => $chartlogo2); });
$c->bind( $chartlogos, '<Leave>', sub {$c->itemconfigure( $chartlogos, -image => $chartlogo1); });
$c->bind( $chartlogos, '<ButtonPress>', sub {&chart('2')});

my $charts_type_frame = $c->Frame(-background => '#0f134d')->place(-x=>544, -y=>400, -anchor => 'nw');
#$charts_type_frame->Label(-font => 'tab_rus_bold', -text => 'Форма Сигнала:') ->pack(-side=>'left'); 
$charts_type_frame->Radiobutton(-background => '#0f134d', -highlightbackground =>'#0f134d', -highlightcolor=>'#0f134d', 
	-activebackground=>'#0f134d', -activeforeground=>'#0f134d', -borderwidth =>0, 
	-foreground=>'#10f0f0', -font => 'bar_rus', -text => 'P', -value => 'p', -variable => \$chart_type)->pack(-side => 'top');
$charts_type_frame->Radiobutton(-background => '#0f134d', -highlightbackground =>'#0f134d', -highlightcolor=>'#0f134d',
	-activebackground=>'#0f134d', -activeforeground=>'#0f134d', -borderwidth =>0, 
        -foreground=>'#10f0f0', -font => 'bar_rus', -text => 'I', -value => "i", -variable => \$chart_type)->pack(-side => 'bottom');

my $charts_frame = $mw->Optionmenu( -options => [@chart_periods], -variable => \$chart_period_type,
		-font=>'bar_rus', -background => '#0f134d', -foreground => '#10f0f0', -indicatoron => 0, -justify=> 'center',  
               -command => [sub {&chart($chart_period_type)}])->place(-x=>537, -y=>460, -anchor => 'nw');



my $banner;
if ($lang eq 'en_US.UTF-8'){
	$banner = $mw->Photo(-data => &encoded_banner_eng, -format => 'gif');
} else {
	$banner = $mw->Photo(-data => &encoded_gif_banner, -format => 'gif');	
}
my $banner_entire = $c->createImage(10, 497, -image => $banner, -anchor => 'nw', -tags => ['banner']);
if ($os =~ /Win/i){ #system("start http://$url")
        eval "use Win32::FileOp qw(ShellExecute); 1" or die $@; #ShellExecute('http://...');
        eval {
              if ($lang eq 'en_US.UTF-8'){
			$c->bind( $banner_entire, '<ButtonPress>', sub {system("start /b http://macenergia.com")});	
		} else {
			  $c->bind( $banner_entire, '<ButtonPress>', sub {system("start /b http://invertors.ru")});
		}	
        };
} else {
	if ($lang eq 'en_US.UTF-8'){
		$c->bind( $banner_entire, '<ButtonPress>', sub {system("firefox http://macenergia.com")})	
	} else {
		$c->bind( $banner_entire, '<ButtonPress>', sub {system("firefox http://invertors.ru")});
	}
}
$c->bind( $banner_entire, '<Any-Enter>', sub {$banner_entire=$c->configure(-cursor=>'hand2')});
$c->bind( $banner_entire, '<Any-Leave>', sub {$banner_entire=$c->configure(-cursor=>'')});

&connect unless ($disconnected);
&readings;
#my $map_version = &readmap('6') unless ($port_not_opening); #power
#my %device_qty = ( '0' => '1','1'=>'2','2'=>'4');
#$qty = $device_qty{$map_version};
$qty = 1 unless ($qty);

#print "qty=$qty\n";

my $dial_0 = $c->createText( 56, 233, -text  => 9*$qty, -font  => 'ticks', -fill  => '#f1f3f0', -anchor => 'nw');
my $dial_16 = $c->createText( 72, 180, -text  => 10*$qty, -font  => 'ticks', -fill  => '#f1f3f0', -anchor => 'nw');
my $dial_33 = $c->createText( 111, 147, -text  => 11*$qty, -font  => 'ticks', -fill  => '#f1f3f0', -anchor => 'nw');
my $dial_50 = $c->createText( 160, 134, -text  => 12*$qty, -font  => 'ticks', -fill  => '#f1f3f0', -anchor => 'nw');
my $dial_66 = $c->createText( 210, 148, -text  => 13*$qty, -font  => 'ticks', -fill  => '#f1f3f0', -anchor => 'nw');
my $dial_79 = $c->createText( 247, 181, -text  => 14*$qty, -font  => 'ticks', -fill  => '#f1f3f0', -anchor => 'nw');

@voltage_acc_charge_end = map {if (looks_like_number($_)){$_*$qty} else {$_}} @voltage_acc_charge_end;
@voltage_acc_sust_charge = map {if (looks_like_number($_)){$_*$qty} else {$_}} @voltage_acc_sust_charge;
@voltage_acc_charge_start = map {if (looks_like_number($_)){$_*$qty} else {$_}} @voltage_acc_charge_start;
@voltage_acc_gen_end = map {if (looks_like_number($_)){$_*$qty} else {$_}} @voltage_acc_gen_end;
@voltage_min_extra_gen_level = map {if (looks_like_number($_)){$_*$qty} else {$_}} @voltage_min_extra_gen_level;



sub tabbed {
	return if Exists($tbd);

	#my $bg_frame = $mw -> Frame() -> place(-x=>0, -y=>0, -anchor => 'nw');
	#my $bg_static = $bg_frame->Photo(-file => '/home/pasha/perl/tk/bg_static.png', -format => 'png');
	#my $shade = $c->createImage(0, 0, -image => $bg_static, -anchor => 'nw', -tags => ['steamy']);
	#$c->raise($bg_static);
	#$frame_power->destroy;
	#$frame_temp_batt->destroy;
	#$frame_batt->destroy;

	$font_counter++;
	$tbd = $mw -> Toplevel();
	$tbd->Icon(-image => $ico);
	$tbd -> geometry( "750x455" ); #460
	$tbd -> optionAdd("*font", "*utf-8");
	#$tbd->protocol(WM_DELETE_WINDOW => sub { $c->lower($shade); $tbd->destroy;  });
	#$nb = $mw->NoteBook(-font => 'Courier 10 bold')->pack
	#$tbd -> optionAdd('*font', -family => 'nimbus sans l', -weight => 'normal', -size=>int(-11*11/10));
	$tbd->fontCreate('tab_rus', -family => 'nimbus sans l', -weight => 'normal', -size=>int(-13*13/10)) unless ($font_counter >1);
	$tbd->fontCreate('tab_rus_bold', -family => 'nimbus sans l', -weight => 'bold', -size=>int(-14*14/10)) unless ($font_counter >1);
	$tbd->fontCreate('tab_rus_tiny', -family => 'nimbus sans l', -weight => 'bold', -size=>int(-9*9/10)) unless ($font_counter >1);
	$tbd->fontCreate('tab_rus_small', -family => 'nimbus sans l', -weight => 'bold', -size=>int(-10*10/10)) unless ($font_counter >1);
	if ($lang eq 'en_US.UTF-8'){
		$tbd -> title ('MAC Preferences');
	} else {
		$tbd -> title ('Настройки МАП');
	}
	#$tbd->bind("<MouseWheel>");

	my $book = $tbd->NoteBook(-font=>'tab_rus', -ipady=>15, )->pack( -fill=>'both');
	
	my ($tab1, $tab2, $tab3, $tab4, $tab5);
	if ($lang eq 'en_US.UTF-8'){
		$tab1 = $book->add( "Sheet 1", -wraplength=>'100', -label=>'Generation');
                $tab2 = $book->add( "Sheet 2", -wraplength=>'100', -label=>'Battery');
                $tab3 = $book->add( "Sheet 3", -wraplength=>'100', -label=>'Grid');
                $tab4 = $book->add( "Sheet 4", -wraplength=>'100', -label=>'More');
                $tab5 = $book->add( "Sheet 5", -wraplength=>'100',-label=>'Help');
	} else {
		$tab1 = $book->add( "Sheet 1", -wraplength=>'100', -label=>'Генерация МАП');
		$tab2 = $book->add( "Sheet 2", -wraplength=>'100', -label=>'Параметры АКБ');
		$tab3 = $book->add( "Sheet 3", -wraplength=>'100', -label=>'Сеть');
		$tab4 = $book->add( "Sheet 4", -wraplength=>'100', -label=>'Другие Опции');
		$tab5 = $book->add( "Sheet 5", -wraplength=>'100',-label=>'Помощь');
	}
	#my ($starttime, $raisetime);

	my $signal_form_frame = $tab1->Frame()->pack(-side=>'top', -anchor=>'nw', -padx=>'15');
	if ($lang eq 'en_US.UTF-8'){
		$signal_form_frame->Label(-font => 'tab_rus_bold', -text => 'Signal form:') ->pack(-side=>'left');	
	} else {
		$signal_form_frame->Label(-font => 'tab_rus_bold', -text => 'Форма Сигнала:')
		->pack(-side=>'left'); #addr 0x138 = 312 //0 - Чистый Sin 5%, 1- Оптимальный Sin 5% до 200В, 2 -Pmx Sin 20%
	}
	$signal_form_frame->Radiobutton(-font => 'tab_rus', -text => 'Sin', -value => '0', -variable => \$signal_form, -command => sub {&write_map('312','0')})
		->pack(-side => 'left');
	if ($lang eq 'en_US.UTF-8'){
		$signal_form_frame->Radiobutton(-font => 'tab_rus', -text => 'Optimal Sine', -value => "1", -variable => \$signal_form, 
                -command => sub {&write_map('312','1')}) ->pack(-side => 'left');
	} else {
        	$signal_form_frame->Radiobutton(-font => 'tab_rus', -text => 'Оптимальный Sin', -value => "1", -variable => \$signal_form, 
		-command => sub {&write_map('312','1')}) ->pack(-side => 'left');
	}
	$signal_form_frame->Radiobutton(-font => 'tab_rus', -text => 'Pmax sin', -value => "2", -variable => \$signal_form, -command => sub {&write_map('312',2)})
	->pack(-side => 'left');
	my $load_start_frame=$tab1->Frame()->pack(-side=>'top', -anchor=>'nw', -after=>$signal_form_frame, -padx=>'15');	
	if ($lang eq 'en_US.UTF-8'){
		$load_start_frame->Label(-font => 'tab_rus_bold', -text=>'Start-Generating-On-Load (' )->pack(-side => 'left');
	} else {
		$load_start_frame->Label(-font => 'tab_rus_bold', -text=>'Вкл по Нагрузке (' )->pack(-side => 'left');
	}
	$load_start_frame->Label(-font => 'tab_rus_bold', -textvariable=>\$load_start )->pack(-side => 'left'); #0x13E = 318
	if ($lang eq 'en_US.UTF-8'){
		$load_start_frame->Label(-font => 'tab_rus_bold', -text=>' Wt)' )->pack(-side => 'left');
	} else {
		$load_start_frame->Label(-font => 'tab_rus_bold', -text=>' Вт)' )->pack(-side => 'left');	
	}
	$load_start_frame->Spinbox(-font => 'tab_rus',-from=>0, -to=>200, -increment=>10, -width=>3, -textvariable=>\$load_start,
		-command => [sub {&write_map('318', $load_start)}])->pack(-side=>'left');


	my $gen_end_frame=$tab1->Frame()->pack(-side=>'top', -anchor=>'nw', -after=>$load_start_frame, -padx=>'15');
	if ($lang eq 'en_US.UTF-8'){
		$gen_end_frame->Label(-font => 'tab_rus_bold', -text=>'Generation-Off V batt min (' )->pack(-side => 'left');
	} else {
		$gen_end_frame->Label(-font => 'tab_rus_bold', -text=>'ВыклГенерации Uакб min (' )->pack(-side => 'left');
	}
        $gen_end_frame->Label(-font => 'tab_rus_bold', -textvariable=>\$map_voltage_acc_gen_end )->pack(-side => 'left'); #0x13d = 317
	if ($lang eq 'en_US.UTF-8'){
		$gen_end_frame->Label(-font => 'tab_rus_bold', -text=>'V): ')->pack(-side => 'left');
	} else {
		$gen_end_frame->Label(-font => 'tab_rus_bold', -text=>'В): ')->pack(-side => 'left');
	}
        $gen_end_frame->Optionmenu( -options => [@voltage_acc_gen_end], -variable => \$map_voltage_acc_gen_end, -font => 'tab_rus',
                -command => [sub {&write_voltage_acc('317', $map_voltage_acc_gen_end)}])->pack(-side=>'left');
	if ($lang eq 'en_US.UTF-8'){
		$gen_end_frame->Label(-font => 'tab_rus_bold', -text=>' Vdc')->pack(-side => 'left');
	} else {
		$gen_end_frame->Label(-font => 'tab_rus_bold', -text=>' В')->pack(-side => 'left');
	}

	my $map_voltage_frame=$tab1->Frame()->pack(-side=>'top', -anchor=>'nw', -after=>$gen_end_frame, -padx=>'15');
	if ($lang eq 'en_US.UTF-8'){
		$map_voltage_frame->Label(-font => 'tab_rus_bold', -text=>'MAC Voltage (')->pack(-side => 'left');
	} else {
		$map_voltage_frame->Label(-font => 'tab_rus_bold', -text=>'Напряжение МАП (')->pack(-side => 'left');
	}
	$map_voltage_frame->Label(-font => 'tab_rus_bold', -textvariable=>\$map_voltage_generated )->pack(-side => 'left'); #0x13a=314
	if ($lang eq 'en_US.UTF-8'){
		$map_voltage_frame->Label(-font => 'tab_rus_bold', -text=>'V): ')->pack(-side => 'left');	
	} else {
		$map_voltage_frame->Label(-font => 'tab_rus_bold', -text=>'В): ')->pack(-side => 'left');
	}
	$map_voltage_frame->Optionmenu( -options => [@voltage_generated], -variable => \$map_voltage_generated, -font => 'tab_rus', 
		-command => [sub {&write_voltage('314', $map_voltage_generated)}])->pack(-side=>'left');
	if ($lang eq 'en_US.UTF-8'){
		$map_voltage_frame->Label(-font => 'tab_rus_bold', -text=>' Vac')->pack(-side => 'left');
	} else {
		$map_voltage_frame->Label(-font => 'tab_rus_bold', -text=>' В')->pack(-side => 'left');
	}
	my $map_voltage_frame_text=$tab1->Frame()->pack(-side=>'top', -anchor=>'nw', -after=>$map_voltage_frame, -padx=>'15');
	if ($lang eq 'en_US.UTF-8'){
		$map_voltage_frame_text->Label(-font => 'tab_rus', -text=>'Firmware versions lower 8.5 need reboot of MAC and display incorrect data!')->
                pack(-side=>'left');
	} else {
		$map_voltage_frame_text->Label(-font => 'tab_rus', -text=>'Прошивки версиий ниже 8.5 требуют перезагрузки и некорректно выдают данные!')->
		pack(-side=>'left');
	}
	my $map_voltage_frame_text2=$tab1->Frame()->pack(-side=>'top', -anchor=>'nw', -after=>$map_voltage_frame_text, -padx=>'15');
	if ($lang eq 'en_US.UTF-8'){
		$map_voltage_frame_text2->Label(-font => 'tab_rus', -text=>'Please download and install the latest firmware from macenergia.com')->
                pack(-side=>'left');
	} else {
		$map_voltage_frame_text2->Label(-font => 'tab_rus', -text=>'Скачайте и обновите прошивку: раздел "техподдрежка" сайта invertors.ru')->
                pack(-side=>'left');
	}
	my ($reset1, $reset2, $reset3);
	if ($lang eq 'en_US.UTF-8'){
		$reset1=$tab1->Button( -text=>'Reboot MAC', -command=>sub {&write_map('0','6')}, -font => 'tab_rus'
                )->pack(-side=>'left', -anchor=>'nw', -after=>$map_voltage_frame_text2, -pady=>'15', -padx=>'15');

                $reset2=$tab1->Button( -text=>'MAC PowerON', -command=>sub {&write_map('0','2')}, -font => 'tab_rus'
                )->pack(-side=>'left', -anchor=>'nw', -padx=>'15', -pady=>'15');
        
                $reset3=$tab1->Button( -text=>'MAC PowerOFF', -command=>sub {&write_map('0','1')}, -font => 'tab_rus'
                )->pack(-side=>'left', -anchor=>'nw', -padx=>'15', -pady=>'15');
	} else {
		$reset1=$tab1->Button( -text=>'Перезагрузить', -command=>sub {&write_map('0','6')}, -font => 'tab_rus' 
		)->pack(-side=>'left', -anchor=>'nw', -after=>$map_voltage_frame_text2, -pady=>'15', -padx=>'15');

		$reset2=$tab1->Button( -text=>'Вкл', -command=>sub {&write_map('0','2')}, -font => 'tab_rus'
        	)->pack(-side=>'left', -anchor=>'nw', -padx=>'15', -pady=>'15');
	
		$reset3=$tab1->Button( -text=>'ВЫкл', -command=>sub {&write_map('0','1')}, -font => 'tab_rus'
        	)->pack(-side=>'left', -anchor=>'nw', -padx=>'15', -pady=>'15');
	}


	#$tab1->Button( -text=>'Выход', -command=>[$tbd => 'destroy'] )->pack(-side=>'top', -anchor=>'center', -after=>$reset, -pady=>'15');



	my $acc_type_frame = $tab2->Frame()->pack(-side=>'top', -anchor=>'nw', -padx=>'15');			#tab 2
	if ($lang eq 'en_US.UTF-8'){
		$acc_type_frame->Label(-font => 'tab_rus_bold', -text => 'Battery type:')
                ->pack(-side=>'left');
	} else {
		$acc_type_frame->Label(-font => 'tab_rus_bold', -text => 'Тип АКБ:')
		->pack(-side=>'left'); #define EE_LCD_AccType 0- Кислотный Рег, 1- Гелевый/AGM T , 2- Кислотный T, //3- Щелочной
	}
	if ($lang eq 'en_US.UTF-8'){
		$acc_type_frame->Radiobutton(-font => 'tab_rus', -text => 'Acid Reg', -value => '0', -variable => \$acc_type,
                -command => sub {&write_map('384','0')})
                ->pack(-side=>'left');
		$acc_type_frame->Radiobutton(-font => 'tab_rus', -text => 'Gel/AGM T', -value => '1', -variable => \$acc_type, -command => sub {&write_map('384','1')})
                ->pack(-side=>'left');
                $acc_type_frame->Radiobutton(-font => 'tab_rus', -text => 'Acid T', -value => '2', -variable => \$acc_type, -command => sub {&write_map('384','2')})
                ->pack(-side=>'left');
                $acc_type_frame->Radiobutton(-font => 'tab_rus', -text => 'Alcaline', -value => '3', -variable => \$acc_type,
                -command => sub {&write_map('384','3')})
                ->pack(-side=>'left');
	} else {
		$acc_type_frame->Radiobutton(-font => 'tab_rus', -text => 'Кислотный Рег', -value => '0', -variable => \$acc_type,
                -command => sub {&write_map('384','0')})
                ->pack(-side=>'left');
		$acc_type_frame->Radiobutton(-font => 'tab_rus', -text => 'Гелевый/AGM T', -value => '1', -variable => \$acc_type, -command => sub {&write_map('384','1')})
		->pack(-side=>'left');
		$acc_type_frame->Radiobutton(-font => 'tab_rus', -text => 'Кислотный Т', -value => '2', -variable => \$acc_type, -command => sub {&write_map('384','2')})
		->pack(-side=>'left');
		$acc_type_frame->Radiobutton(-font => 'tab_rus', -text => 'Щелочной', -value => '3', -variable => \$acc_type, 
		-command => sub {&write_map('384','3')})
		->pack(-side=>'left');
	}
	my $acc_type_wording_frame = $tab2->Frame()->pack(-side=>'top', -anchor=>'nw', -padx=>'5', -after=>$acc_type_frame);
        
	my $acc_charge_start_frame = $tab2->Frame()->pack(-side=>'top', -anchor=>'nw', -padx=>'15', -after=>$acc_type_frame);
	if ($lang eq 'en_US.UTF-8'){
		$acc_charge_start_frame->Label(-font => 'tab_rus_bold', -text=>'* Start Charge at (' )->pack(-side=>'left');
	} else {
		$acc_charge_start_frame->Label(-font => 'tab_rus_bold', -text=>'* Старт Заряда (' )->pack(-side=>'left'); #0x16c
	}
        $acc_charge_start_frame->Label(-font => 'tab_rus_bold', -textvariable=>\$map_acc_charge_start )->pack(-side => 'left'); #0x187 = 391
	if ($lang eq 'en_US.UTF-8'){
		$acc_charge_start_frame->Label(-font => 'tab_rus_bold', -text=>'V): ')->pack(-side => 'left');
	} else {
	        $acc_charge_start_frame->Label(-font => 'tab_rus_bold', -text=>'В): ')->pack(-side => 'left');
        }
	$acc_charge_start_frame->Optionmenu( -options => [@voltage_acc_charge_start], -variable => \$map_acc_charge_start, -font => 'tab_rus',
                -command => [sub {&write_voltage_acc('391', $map_acc_charge_start)}])->pack(-side=>'left');
	if ($lang eq 'en_US.UTF-8'){
		$acc_charge_start_frame->Label(-font => 'tab_rus_bold', -text=>' Vdc')->pack(-side => 'left');
	} else {
        	$acc_charge_start_frame->Label(-font => 'tab_rus_bold', -text=>' В')->pack(-side => 'left');
	}
        my $acc_charge_sust_frame = $tab2->Frame()->pack(-side=>'top', -anchor=>'nw', -padx=>'15', -after=>$acc_charge_start_frame);
	if ($lang eq 'en_US.UTF-8'){
		$acc_charge_sust_frame->Label(-font => 'tab_rus_bold', -text=>'* Sustain Charge (' )->pack(-side=>'left');
	} else {
        	$acc_charge_sust_frame->Label(-font => 'tab_rus_bold', -text=>'* Поддерживающий Заряд (' )->pack(-side=>'left');
	}
        $acc_charge_sust_frame->Label(-font => 'tab_rus_bold', -textvariable=>\$map_acc_sust_charge )->pack(-side => 'left'); #0x186 = 390
	if ($lang eq 'en_US.UTF-8'){
		$acc_charge_sust_frame->Label(-font => 'tab_rus_bold', -text=>'V): ')->pack(-side => 'left');
	} else {
        	$acc_charge_sust_frame->Label(-font => 'tab_rus_bold', -text=>'В): ')->pack(-side => 'left');
	}
        $acc_charge_sust_frame->Optionmenu(-options => [@voltage_acc_sust_charge], -variable => \$map_acc_sust_charge, -font => 'tab_rus',
                -command => [sub {&write_voltage_acc('390', $map_acc_sust_charge)}])->pack(-side=>'left');
	if ($lang eq 'en_US.UTF-8'){
		$acc_charge_sust_frame->Label(-font => 'tab_rus_bold', -text=>' Vdc')->pack(-side => 'left');
	} else {
        	$acc_charge_sust_frame->Label(-font => 'tab_rus_bold', -text=>' В')->pack(-side => 'left');
	}
        my $acc_charge_end_frame = $tab2->Frame()->pack(-side=>'top', -anchor=>'nw', -padx=>'15', -after=>$acc_charge_sust_frame);
	if ($lang eq 'en_US.UTF-8'){
		$acc_charge_end_frame->Label(-font => 'tab_rus_bold', -text=>'* End Charge (' )->pack(-side=>'left')	
	} else {
        	$acc_charge_end_frame->Label(-font => 'tab_rus_bold', -text=>'* Конечный Заряд (' )->pack(-side=>'left');
	}
        $acc_charge_end_frame->Label(-font => 'tab_rus_bold', -textvariable=>\$map_acc_charge_end )->pack(-side => 'left'); #0x185 = 389
	if ($lang eq 'en_US.UTF-8'){
		$acc_charge_end_frame->Label(-font => 'tab_rus_bold', -text=>'Vdc): ')->pack(-side => 'left');
	} else {
	        $acc_charge_end_frame->Label(-font => 'tab_rus_bold', -text=>'В): ')->pack(-side => 'left');
        }
	$acc_charge_end_frame->Optionmenu(-options => [@voltage_acc_charge_end], -variable => \$map_acc_charge_end, -font => 'tab_rus',
                -command => [sub {&write_voltage_acc('389', $map_acc_charge_end)}])->pack(-side=>'left');
	if ($lang eq 'en_US.UTF-8'){
		$acc_charge_end_frame->Label(-font => 'tab_rus_bold', -text=>' Vdc')->pack(-side => 'left');
		$acc_type_wording_frame->Label(-font => 'tab_rus', -text => '* for acid and alcaline batteries olny')
                ->pack(-side=>'left');
	} else {
	        $acc_charge_end_frame->Label(-font => 'tab_rus_bold', -text=>' В')->pack(-side => 'left');
		$acc_type_wording_frame->Label(-font => 'tab_rus', -text => '* параметры только для кислотных и щелочных АКБ')
                ->pack(-side=>'left');
	}


	my $charge_alg_frame_text = $tab2->Frame()->pack(-side=>'top', -anchor=>'nw', -padx=>'15', -after=>$acc_type_wording_frame);
	if ($lang eq 'en_US.UTF-8'){
		$charge_alg_frame_text->Label(-font => 'tab_rus_bold', -text => 'Charge Type:')->pack(-side=>'left');
	} else {
		$charge_alg_frame_text->Label(-font => 'tab_rus_bold', -text => 'Алгоритм Заряда:')->pack(-side=>'left');
	}
	
	my $charge_alg_frame = $tab2->Frame()->pack(-side=>'top', -anchor=>'nw', -after=>$charge_alg_frame_text, -padx=>'35'); 
	my ($charge_alg_frame_2);
	if ($lang eq 'en_US.UTF-8'){
		$charge_alg_frame->Radiobutton(-font => 'tab_rus', -text => '2 Stages 2-currents', -value => '0', -variable => \$charge_alg,
                -command => sub {&write_map('388','0')})->pack(-side=>'left');
                $charge_alg_frame->Radiobutton(-font => 'tab_rus', -text => '3 Stages 2-currents+ExtraCharge', -value => '1', -variable => \$charge_alg,
                -command => sub {&write_map('388','1')})
                ->pack(-side=>'left', -expand=>1);
                $charge_alg_frame_2 = $tab2->Frame()->pack(-side=>'top', -anchor=>'nw', -after=>$charge_alg_frame, -padx=>'35');
                $charge_alg_frame_2->Radiobutton(-font => 'tab_rus', -text => '2 - 3 Stages 2-currents+BufferCharge', -value => '2', -variable => \$charge_alg,
                -command => sub {&write_map('388','2')})->pack(-side=>'left');
                $charge_alg_frame_2->Radiobutton(-font => 'tab_rus', -text => '4 Stages 2-currents+ExtraCharge+BufferCharge', -value => '3', -variable => \$charge_alg,
                -command => sub {&write_map('388','3')})->pack(-side=>'left');
	} else {
		$charge_alg_frame->Radiobutton(-font => 'tab_rus', -text => '2 Ступен 2-тока', -value => '0', -variable => \$charge_alg,  
		-command => sub {&write_map('388','0')})->pack(-side=>'left');
        	$charge_alg_frame->Radiobutton(-font => 'tab_rus', -text => '3 Ступени 2-тока+Дозаряд', -value => '1', -variable => \$charge_alg, 
		-command => sub {&write_map('388','1')})
		->pack(-side=>'left', -expand=>1);
		$charge_alg_frame_2 = $tab2->Frame()->pack(-side=>'top', -anchor=>'nw', -after=>$charge_alg_frame, -padx=>'35');
        	$charge_alg_frame_2->Radiobutton(-font => 'tab_rus', -text => '2 - 3 Ступени 2-тока+Буферный', -value => '2', -variable => \$charge_alg, 
		-command => sub {&write_map('388','2')})->pack(-side=>'left');
        	$charge_alg_frame_2->Radiobutton(-font => 'tab_rus', -text => '4 Ступени 2-тока+Дозаряд+Буфер', -value => '3', -variable => \$charge_alg, 
		-command => sub {&write_map('388','3')})->pack(-side=>'left');
	}

	my $current_start_charge_frame=$tab2->Frame()->pack(-side=>'top', -anchor=>'nw', -after=>$charge_alg_frame_2, -padx=>'15');
	if ($lang eq 'en_US.UTF-8'){
		$current_start_charge_frame->Label(-font => 'tab_rus_bold', -text=>'Initial Charge Current (' )->pack(-side => 'left');
                $current_start_charge_frame->Label(-font => 'tab_rus_bold', -textvariable=>\$current_start_charge )->pack(-side => 'left'); #0x182 = 386 
                $current_start_charge_frame->Label(-font => 'tab_rus_bold', -text=>'C)' )->pack(-side => 'left');
                $current_start_charge_frame->Spinbox(-font => 'tab_rus',-from=>0.1, -to=>0.2, -increment=>0.01, -width=>4, -textvariable=>\$current_start_charge,
                -command => [sub {&write_current('386', $current_start_charge)}])->pack(-side=>'left');
	} else {
        	$current_start_charge_frame->Label(-font => 'tab_rus_bold', -text=>'Ток Заряда Начальный (' )->pack(-side => 'left');
        	$current_start_charge_frame->Label(-font => 'tab_rus_bold', -textvariable=>\$current_start_charge )->pack(-side => 'left'); #0x182 = 386 
        	$current_start_charge_frame->Label(-font => 'tab_rus_bold', -text=>'C)' )->pack(-side => 'left');
        	$current_start_charge_frame->Spinbox(-font => 'tab_rus',-from=>0.1, -to=>0.2, -increment=>0.01, -width=>4, -textvariable=>\$current_start_charge,
                -command => [sub {&write_current('386', $current_start_charge)}])->pack(-side=>'left');	
	}

	my $current_end_charge_frame=$tab2->Frame()->pack(-side=>'top', -anchor=>'nw', -after=>$current_start_charge_frame, -padx=>'15');
	if ($lang eq 'en_US.UTF-8'){
		$current_end_charge_frame->Label(-font => 'tab_rus_bold', -text=>'Final Charge Current (' )->pack(-side => 'left');
	} else {
        	$current_end_charge_frame->Label(-font => 'tab_rus_bold', -text=>'Ток Заряда Конечный (' )->pack(-side => 'left');
	}
        $current_end_charge_frame->Label(-font => 'tab_rus_bold', -textvariable=>\$current_end_charge )->pack(-side => 'left'); #0x183 = 387 
        $current_end_charge_frame->Label(-font => 'tab_rus_bold', -text=>'C)' )->pack(-side => 'left');
        $current_end_charge_frame->Spinbox(-font => 'tab_rus',-from=>0.01, -to=>0.06, -increment=>0.01, -width=>4, -textvariable=>\$current_end_charge,
                -command => [sub {&write_current('387', $current_end_charge)}])->pack(-side=>'left');

	my $capacity_entire_frame=$tab2->Frame()->pack(-side=>'top', -anchor=>'nw', -after=>$current_end_charge_frame, -padx=>'15');
	if ($lang eq 'en_US.UTF-8'){
		$capacity_entire_frame->Label(-font => 'tab_rus_bold', -text=>'Total Battery Capacity (' )->pack(-side => 'left');	
	} else {
	        $capacity_entire_frame->Label(-font => 'tab_rus_bold', -text=>'Суммарная Ёмкость (' )->pack(-side => 'left');
        }
	$capacity_entire_frame->Label(-font => 'tab_rus_bold', -textvariable=>\$capacity_entire )->pack(-side => 'left'); #0x181 = 385 
        $capacity_entire_frame->Label(-font => 'tab_rus_bold', -text=>'C)' )->pack(-side => 'left');
        $capacity_entire_frame->Spinbox(-font => 'tab_rus',-from=>40, -to=>2000, -increment=>10, -width=>4, -textvariable=>\$capacity_entire,
                -command => [sub {&write_capacity('385', $capacity_entire)}])->pack(-side=>'left');

	my ($charge_on, $charge_off);
	if ($lang eq 'en_US.UTF-8'){
		$charge_on=$tab2->Button( -text=>'Charge On', -command=>sub {&write_map('0','5')}, -font => 'tab_rus'
                )->pack(-side=>'left', -anchor=>'nw', -padx=>'15', -pady=>'15');

                $charge_off=$tab2->Button( -text=>'Charge Off', -command=>sub {&write_map('0','4')}, -font => 'tab_rus'
                )->pack(-side=>'left', -anchor=>'nw', -padx=>'15', -pady=>'15');
	} else {
		$charge_on=$tab2->Button( -text=>'Включить Заряд', -command=>sub {&write_map('0','5')}, -font => 'tab_rus'
        	)->pack(-side=>'left', -anchor=>'nw', -padx=>'15', -pady=>'15');

        	$charge_off=$tab2->Button( -text=>'ВЫключить Заряд', -command=>sub {&write_map('0','4')}, -font => 'tab_rus'
        	)->pack(-side=>'left', -anchor=>'nw', -padx=>'15', -pady=>'15');
	}


	#tab3

	my $net_type_frame=$tab3->Frame()->pack(-side=>'top', -anchor=>'nw', -padx=>'15'); #top of tab 3!
        if ($lang eq 'en_US.UTF-8'){
		$net_type_frame->Label(-font => 'tab_rus_bold', -text=>'Grid / Generator Power (' )->pack(-side => 'left');
                $net_type_frame->Label(-font => 'tab_rus_bold', -textvariable=>\$net_type_label )->pack(-side => 'left'); #0x168 = 360 
                $net_type_frame->Label(-font => 'tab_rus_bold', -text=>'Wt)' )->pack(-side => 'left');
                $net_type_frame->Spinbox(-font => 'tab_rus_bold',-from=>0, -to=>9.9, -increment=>0.1, -width=>4, -textvariable=>\$net_type_label, -font => 'tab_rus',
                -command => [sub {&write_net_type('360', $net_type_label)}])->pack(-side=>'left');
	} else {
		$net_type_frame->Label(-font => 'tab_rus_bold', -text=>'Сеть / Мощность Генератора (' )->pack(-side => 'left');
        	$net_type_frame->Label(-font => 'tab_rus_bold', -textvariable=>\$net_type_label )->pack(-side => 'left'); #0x168 = 360 
        	$net_type_frame->Label(-font => 'tab_rus_bold', -text=>'Вт)' )->pack(-side => 'left');
        	$net_type_frame->Spinbox(-font => 'tab_rus_bold',-from=>0, -to=>9.9, -increment=>0.1, -width=>4, -textvariable=>\$net_type_label, -font => 'tab_rus',
                -command => [sub {&write_net_type('360', $net_type_label)}])->pack(-side=>'left');
        	#$net_type_frame->Label(-font => 'tab_rus_bold', -text=>' [0В - Пром. Сеть]' )->pack(-side => 'left');
	}
	my $net_type_frame_extra=$tab3->Frame()->pack(-side=>'top', -anchor=>'nw', -padx=>'15',-after=>$net_type_frame);
	if ($lang eq 'en_US.UTF-8'){
		$net_type_frame_extra->Label(-font => 'tab_rus', -text=>'To select "Grid" set Power level to zero' )->pack(-side => 'left');
	} else {
		$net_type_frame_extra->Label(-font => 'tab_rus', -text=>'Установите мощность равную "0" чтобы выбрать "Промышленная Сеть"' )->pack(-side => 'left');
	}
	my $time_savings_begin_frame = $tab3->Frame()->pack(-side=>'top', -anchor=>'nw', -padx=>'15', -after=>$net_type_frame_extra);
        $time_savings_begin_frame->Label(-font => 'tab_rus_bold', -textvariable=> \$time_savings_begin_label)->pack(-side=>'left'); #0x16d = 365
        $time_savings_begin_hours='-';
        $time_savings_begin_minutes='-';
        $time_savings_begin_frame->Optionmenu( -options => \@hour_labels, -variable => \$time_savings_begin_hours, -font => 'tab_rus', 
		-command => [sub {&write_time('365', $time_savings_begin_hours, $time_savings_begin_minutes)}])->
                pack(-side=>'left'); 
        $time_savings_begin_frame->Label(-font => 'tab_rus_bold', -text => ' : ')->pack(-side=>'left');
        $time_savings_begin_frame->Optionmenu( -options => \@minute_labels, -variable => \$time_savings_begin_minutes, -font => 'tab_rus',
		-command => [sub {&write_time('365', $time_savings_begin_hours, $time_savings_begin_minutes)}])->
                pack(-side=>'left');

	my $time_savings_end_frame = $tab3->Frame()->pack(-side=>'top', -anchor=>'nw', -padx=>'15', -after=>$time_savings_begin_frame); #$tab3
        $time_savings_end_frame->Label(-font => 'tab_rus_bold', -textvariabl => \$time_savings_end_label)->pack(-side=>'left'); #0x16e = 366
        $time_savings_end_hours='-';
        $time_savings_end_minutes='-';
        $time_savings_end_frame->Optionmenu( -options => \@hour_labels, -variable => \$time_savings_end_hours, -font => 'tab_rus',
		-command => [sub {&write_time('366', $time_savings_end_hours, $time_savings_end_minutes)}])->pack(-side=>'left');
        $time_savings_end_frame->Label(-font => 'tab_rus_bold', -text => ' : ')->pack(-side=>'left');
        $time_savings_end_frame->Optionmenu( -options => \@minute_labels, -variable => \$time_savings_end_minutes, -font => 'tab_rus', 
		-command => [sub {&write_time('366', $time_savings_end_hours, $time_savings_end_minutes)}])->pack(-side=>'left');
	
        my $u_min_extra_gen_frame = $tab3->Frame()->pack(-side=>'top', -anchor=>'nw', -padx=>'15', -after=>$time_savings_end_frame);
	if ($lang eq 'en_US.UTF-8'){
		$u_min_extra_gen_frame->Label( -font => 'tab_rus_bold', -text=>'Vmin Enorced Generation (ECO) (' )->pack(-side=>'left'); #0x16c
                $u_min_extra_gen_frame->Label(-font => 'tab_rus_bold', -textvariable=>\$map_min_extra_gen_level )->pack(-side => 'left'); #0x16c = 364
                $u_min_extra_gen_frame->Label(-font => 'tab_rus_bold', -text=>'V): ')->pack(-side => 'left');
                $u_min_extra_gen_frame->Optionmenu( -options => [@voltage_min_extra_gen_level], -variable => \$map_min_extra_gen_level, -font => 'tab_rus',
                        -command => [sub {&write_voltage_acc('364', $map_min_extra_gen_level)}])->pack(-side=>'left');
                $u_min_extra_gen_frame->Label(-font => 'tab_rus_bold', -text=>' Vac')->pack(-side => 'left');
	} else {
	        $u_min_extra_gen_frame->Label( -font => 'tab_rus_bold', -text=>'Umin Принуд Генер (' )->pack(-side=>'left'); #0x16c
        	$u_min_extra_gen_frame->Label(-font => 'tab_rus_bold', -textvariable=>\$map_min_extra_gen_level )->pack(-side => 'left'); #0x16c = 364
        	$u_min_extra_gen_frame->Label(-font => 'tab_rus_bold', -text=>'В): ')->pack(-side => 'left');
        	$u_min_extra_gen_frame->Optionmenu( -options => [@voltage_min_extra_gen_level], -variable => \$map_min_extra_gen_level, -font => 'tab_rus',
			-command => [sub {&write_voltage_acc('364', $map_min_extra_gen_level)}])->pack(-side=>'left');
        	$u_min_extra_gen_frame->Label(-font => 'tab_rus_bold', -text=>' В')->pack(-side => 'left');
	}

	my $net_control_frame = $tab3->Frame()->pack(-side=>'top', -anchor=>'nw', -padx=>'15', -after=>$u_min_extra_gen_frame); #tab3
	#$net_control_frame->Label(-textvariable => \$net_control_alg)->pack(-side=>'left');
	my ($net_control_frame_1, $net_control_frame_2);
	if ($lang eq 'en_US.UTF-8'){
		$net_control_frame->Label(-font => 'tab_rus_bold', -text => 'Grid Control:')->pack(-side=>'left'); #0x16b  
                $net_control_frame_1 = $tab3->Frame()->pack(-side=>'top', -anchor=>'nw', -padx=>'35', -after=>$net_control_frame);
                $net_control_frame_1->Radiobutton(-font => 'tab_rus', -text => 'Feed + Charge', -value => '0', -variable => \$net_control_alg,  
                        -command => sub {&write_map('363','0')})->pack(-side=>'left');
                $net_control_frame_1->Radiobutton(-font => 'tab_rus', -text => 'Feed only', -value => '1', -variable => \$net_control_alg,  
                        -command => sub {&write_map('363','1')})->pack(-side=>'left');
                $net_control_frame_2 = $tab3->Frame()->pack(-side=>'top', -anchor=>'nw', -padx=>'35', -after=>$net_control_frame_1);
                $net_control_frame_2->Radiobutton(-font => 'tab_rus', -text => 'Enforced Generation', -value => '2', -variable => \$net_control_alg,  
                        -command => sub {&write_map('363','2')})->pack(-side=>'left');
                $net_control_frame_2->Radiobutton(-font => 'tab_rus', -text => 'Timed Savings Grid', -value => '3', -variable => \$net_control_alg,  
                        -command => sub {&write_map('363','3')})->pack(-side=>'left');
	} else {
		$net_control_frame->Label(-font => 'tab_rus_bold', -text => 'Управление Сетью:')->pack(-side=>'left'); #0x16b 
		$net_control_frame_1 = $tab3->Frame()->pack(-side=>'top', -anchor=>'nw', -padx=>'35', -after=>$net_control_frame);
		$net_control_frame_1->Radiobutton(-font => 'tab_rus', -text => 'Трансляция + Заряд', -value => '0', -variable => \$net_control_alg,  
			-command => sub {&write_map('363','0')})->pack(-side=>'left');
		$net_control_frame_1->Radiobutton(-font => 'tab_rus', -text => 'Только Трансляция', -value => '1', -variable => \$net_control_alg,  
			-command => sub {&write_map('363','1')})->pack(-side=>'left');
		$net_control_frame_2 = $tab3->Frame()->pack(-side=>'top', -anchor=>'nw', -padx=>'35', -after=>$net_control_frame_1);
		$net_control_frame_2->Radiobutton(-font => 'tab_rus', -text => 'Принудительная Генерация', -value => '2', -variable => \$net_control_alg,  
			-command => sub {&write_map('363','2')})->pack(-side=>'left');
		$net_control_frame_2->Radiobutton(-font => 'tab_rus', -text => 'Тарифная Сеть', -value => '3', -variable => \$net_control_alg,  
			-command => sub {&write_map('363','3')})->pack(-side=>'left');
	}

	my $net_level_upper_frame = $tab3->Frame()->pack(-side=>'top', -anchor=>'nw', -padx=>'15', -after=>$net_control_frame_2);
	if ($lang eq 'en_US.UTF-8'){
		$net_level_upper_frame->Label( -font => 'tab_rus_bold', -text=>'Upper Grid Voltage Limit (' )->pack(-side=>'left'); #0x169
                $net_level_upper_frame->Label(-font => 'tab_rus_bold', -textvariable=>\$map_net_level_upper )->pack(-side => 'left'); #0x169 = 361
                $net_level_upper_frame->Label(-font => 'tab_rus_bold', -text=>'V): ')->pack(-side => 'left');
                $net_level_upper_frame->Optionmenu( -options => [@voltage_upper_level], -variable => \$map_net_level_upper, -font => 'tab_rus',
                        -command => [sub {&write_voltage('361', $map_net_level_upper)}])->pack(-side=>'left');
                $net_level_upper_frame->Label(-font => 'tab_rus_bold', -text=>' Vac')->pack(-side => 'left');
	} else {
		$net_level_upper_frame->Label( -font => 'tab_rus_bold', -text=>'Верхний Порог Сети (' )->pack(-side=>'left'); #0x169
		$net_level_upper_frame->Label(-font => 'tab_rus_bold', -textvariable=>\$map_net_level_upper )->pack(-side => 'left'); #0x169 = 361
		$net_level_upper_frame->Label(-font => 'tab_rus_bold', -text=>'В): ')->pack(-side => 'left');
		$net_level_upper_frame->Optionmenu( -options => [@voltage_upper_level], -variable => \$map_net_level_upper, -font => 'tab_rus',
                	-command => [sub {&write_voltage('361', $map_net_level_upper)}])->pack(-side=>'left');
		$net_level_upper_frame->Label(-font => 'tab_rus_bold', -text=>' В')->pack(-side => 'left');
	}
	
	my $net_level_lower_frame = $tab3->Frame()->pack(-side=>'top', -anchor=>'nw', -padx=>'15', -after=>$net_level_upper_frame);
	if ($lang eq 'en_US.UTF-8'){
		$net_level_lower_frame->Label( -font => 'tab_rus_bold', -text=>'Lower Grid Voltage Level (' )->pack(-side=>'left');
                $net_level_lower_frame->Label(-font => 'tab_rus_bold', -textvariable=>\$map_net_level_lower )->pack(-side => 'left'); #0x16a = 362
                $net_level_lower_frame->Label(-font => 'tab_rus_bold', -text=>'V): ')->pack(-side => 'left');
                $net_level_lower_frame->Optionmenu( -options => [@voltage_low_level], -variable => \$map_net_level_lower, -font => 'tab_rus',
                        -command => [sub {&write_voltage('362', $map_net_level_lower)}])->pack(-side=>'left');
                $net_level_lower_frame->Label(-font => 'tab_rus_bold', -text=>' Vac')->pack(-side => 'left');
	} else {
		$net_level_lower_frame->Label( -font => 'tab_rus_bold', -text=>'Нижний Порог Сети (' )->pack(-side=>'left');
		$net_level_lower_frame->Label(-font => 'tab_rus_bold', -textvariable=>\$map_net_level_lower )->pack(-side => 'left'); #0x16a = 362
		$net_level_lower_frame->Label(-font => 'tab_rus_bold', -text=>'В): ')->pack(-side => 'left');
		$net_level_lower_frame->Optionmenu( -options => [@voltage_low_level], -variable => \$map_net_level_lower, -font => 'tab_rus',
			-command => [sub {&write_voltage('362', $map_net_level_lower)}])->pack(-side=>'left');
		$net_level_lower_frame->Label(-font => 'tab_rus_bold', -text=>' В')->pack(-side => 'left');	
	}

	#$tab3->Button( -text=>'Выход', -command=>[$tbd => 'destroy'] )->pack(-side=>'top', -anchor=>'center', -pady=>'15');


	##1b6 define EE_LCD_TimeCyr        0  //Текущее время, например, 23:50 хранится как  - 23- в старших 5 битах, 5- в младших 3 битах
	#                              //т.к. здесь только десятки мин, то дополнительно хранятся минуты в TimeCyr_MINUT 0x1b6 = 438
	my $map_time_frame = $tab4->Frame()->pack(-side=>'top', -anchor=>'nw', -padx=>'15'); #$tab4
	$map_time_frame->Label(-font => 'tab_rus_bold', -textvariable => \$real_time_label)->pack(-side=>'left');
	$time_hours_map='-';
	$time_minutes_map='-';
	$map_time_frame->Optionmenu( -options => \@hour_labels, -variable => \$time_hours_map, -font => 'tab_rus',
		-command => [sub {&write_time('438', $time_hours_map, $time_minutes_map)}])->
		pack(-side=>'left');
	$map_time_frame->Label(-font => 'tab_rus_bold', -text => ' : ')->pack(-side=>'left');
	$map_time_frame->Optionmenu( -options => \@minute_labels, -variable => \$time_minutes_map, -font => 'tab_rus',
		-command => [sub {&write_time('438', $time_hours_map, $time_minutes_map)}])->
		pack(-side=>'left');
	#$map_time_frame->Label(-font => 'tab_rus_bold', -textvariable=>\$times)->pack(-side=>'left');
	my $map_time_frame_extra = $tab4->Frame()->pack(-side=>'top', -anchor=>'nw', -padx=>'15', -after=>$map_time_frame);
	if ($lang eq 'en_US.UTF-8'){
		$map_time_frame_extra->Label(-font => 'tab_rus', -text => '[internal clock settings will be lost on MAC shutdown]')->pack(-side=>'left');
	} else {
		$map_time_frame_extra->Label(-font => 'tab_rus', -text => '[настройки МАП-времени сбрасываются при отключении МАП]')->pack(-side=>'left');
	}
	my $map_version_frame = $tab4->Frame()->pack(-side=>'top', -anchor=>'nw', -after=>$map_time_frame_extra, -padx=>'15');	
	if ($lang eq 'en_US.UTF-8'){
		$map_version_frame->Label( -font => 'tab_rus_bold', -text=>'Version: ' )->pack(-side=>'left');
	} else {
		$map_version_frame->Label( -font => 'tab_rus_bold', -text=>'Версия: ' )->pack(-side=>'left');
	}
	$map_version_frame->Label(-font => 'tab_rus_bold', -textvariable => \$map_versions)->pack(-side=>'left');

	my $map_max_charge_time_frame=$tab4->Frame()->pack(-side=>'top', -anchor=>'nw', -after=>$map_version_frame, -padx=>'15'); #top of tab 3!
	if ($lang eq 'en_US.UTF-8'){
		$map_max_charge_time_frame->Label(-font => 'tab_rus_bold', -text=>'Max Charge Time (' )->pack(-side => 'left');
                $map_max_charge_time_frame->Label(-font => 'tab_rus_bold', -textvariable=>\$map_max_charge_time )->pack(-side => 'left'); #0x168 = 360 
                $map_max_charge_time_frame->Label(-font => 'tab_rus_bold', -text=>'hours)' )->pack(-side => 'left');
                $map_max_charge_time_frame->Spinbox(-font => 'tab_rus',-from=>2, -to=>48, -increment=>2, -width=>3, -textvariable=>\$map_max_charge_time,
                        -command => [sub {&write_charge_time('439', $map_max_charge_time)}])->pack(-side=>'left');
	} else {
        	$map_max_charge_time_frame->Label(-font => 'tab_rus_bold', -text=>'Max Время Заряда (' )->pack(-side => 'left');
        	$map_max_charge_time_frame->Label(-font => 'tab_rus_bold', -textvariable=>\$map_max_charge_time )->pack(-side => 'left'); #0x168 = 360 
        	$map_max_charge_time_frame->Label(-font => 'tab_rus_bold', -text=>'час.)' )->pack(-side => 'left');
        	$map_max_charge_time_frame->Spinbox(-font => 'tab_rus',-from=>2, -to=>48, -increment=>2, -width=>3, -textvariable=>\$map_max_charge_time,
                	-command => [sub {&write_charge_time('439', $map_max_charge_time)}])->pack(-side=>'left');
	}
	my $conn_speed_frame = $tab4->Frame()->pack(-side=>'top', -anchor=>'nw', -after=>$map_max_charge_time_frame, -padx=>'15');#(-side=>'top'); #tab4
	if ($lang eq 'en_US.UTF-8'){
		$conn_speed_frame->Label(-font => 'tab_rus_bold', -text => 'Connection speed RS/SAS/PC:')
                ->pack(-side=>'left');
	} else {
		$conn_speed_frame->Label(-font => 'tab_rus_bold', -text => 'Скорость RS/САП:')
		->pack(-side=>'left');#(-side=>'top'); #2  //01b5= 437 - 2400, 1- 9600, 2 - 19200, 3 - САП-Заряд
	}
	$conn_speed_frame->Radiobutton(-font => 'tab_rus', -text => '2400 B/s', -value => '0', -variable => \$conn_speed,  -command => sub {&write_map('437','0')})
        ->pack(-side=>'left'); #(-side => 'right');
	$conn_speed_frame->Radiobutton(-font => 'tab_rus', -text => '9600 B/s', -value => '1', -variable => \$conn_speed,  -command => sub {&write_map('437','1')})
        ->pack(-side=>'left');#(-side => 'right');
	$conn_speed_frame->Radiobutton(-font => 'tab_rus', -text => '19200 B/s', -value => '2', -variable => \$conn_speed,  -command => sub {&write_map('437','2')})
        ->pack(-side=>'left'); #(-side => 'right');
	

	my $sound_frame = $tab4->Frame()->pack(-side=>'top', -anchor=>'nw', -after=>$conn_speed_frame, -padx=>'15'); #(-side=>'top'); #tab4
	if ($lang eq 'en_US.UTF-8'){
		$sound_frame->Label(-font => 'tab_rus_bold', -text => 'Sounds: ')
                ->pack(-side=>'left'); #(-side=>'top'); #0x1b3=435 0- Разрешенные (без 8), 1 - ТолькоПроблемы (без переходов и без 8), 2- Никаких
                $sound_frame->Radiobutton(-font => 'tab_rus', -text => 'Permitted', -value => '0', -variable => \$sound_control,  
                -command => sub {&write_map('435','0')})->pack(-side=>'left'); #(-side => 'right');
                $sound_frame->Radiobutton(-font => 'tab_rus', -text => 'Problem indication', -value => '1', -variable => \$sound_control,  
                -command => sub {&write_map('435','1')})->pack(-side=>'left'); #(-side => 'right');
                $sound_frame->Radiobutton(-font => 'tab_rus', -text => 'None (no sounds)', -value => '2', -variable => \$sound_control,  
                -command => sub {&write_map('435','2')}) ->pack(-side=>'left'); #(-side => 'right');
	} else {
		$sound_frame->Label(-font => 'tab_rus_bold', -text => 'Звуки: ')
                ->pack(-side=>'left'); #(-side=>'top'); #0x1b3=435 0- Разрешенные (без 8), 1 - ТолькоПроблемы (без переходов и без 8), 2- Никаких
		$sound_frame->Radiobutton(-font => 'tab_rus', -text => 'Разрешенные', -value => '0', -variable => \$sound_control,  
		-command => sub {&write_map('435','0')})->pack(-side=>'left'); #(-side => 'right');
		$sound_frame->Radiobutton(-font => 'tab_rus', -text => 'Только Проблемы', -value => '1', -variable => \$sound_control,  
		-command => sub {&write_map('435','1')})->pack(-side=>'left'); #(-side => 'right');
		$sound_frame->Radiobutton(-font => 'tab_rus', -text => 'Никаких', -value => '2', -variable => \$sound_control,  
		-command => sub {&write_map('435','2')}) ->pack(-side=>'left'); #(-side => 'right');
	}
	my $lcd_backlight_frame = $tab4->Frame()->pack(-side=>'top', -anchor=>'nw', -after=>$sound_frame, -padx=>'15');#(-side=>'top'); #tab4
	if ($lang eq 'en_US.UTF-8'){
		$lcd_backlight_frame->Label(-font => 'tab_rus_bold', -text => 'LCD Backlight:')
                ->pack(-side=>'left'); #(-side=>'top'); #0x1b2=434 define EE_LCD_LCDType        1  //0 - выключен, 1 - горит по ситуации ,2 - всегда горит
                $lcd_backlight_frame->Radiobutton(-font => 'tab_rus', -text => 'Off', -value => '0', -variable => \$lcd_backlight,  
                -command => sub {&write_map('434','0')})->pack(-side=>'left'); #(-side => 'right');
                $lcd_backlight_frame->Radiobutton(-font => 'tab_rus', -text => 'Automatic', -value => '1', -variable => \$lcd_backlight,  
                -command => sub {&write_map('434','1')})->pack(-side=>'left'); #(-side => 'right');
                $lcd_backlight_frame->Radiobutton(-font => 'tab_rus', -text => 'Always On', -value => '2', -variable => \$lcd_backlight,  
                -command => sub {&write_map('434','2')})->pack(-side=>'left'); #(-side => 'right');	
	} else {
		$lcd_backlight_frame->Label(-font => 'tab_rus_bold', -text => 'Подсветка ЖКИ:')
                ->pack(-side=>'left'); #(-side=>'top'); #0x1b2=434 define EE_LCD_LCDType        1  //0 - выключен, 1 - горит по ситуации ,2 - всегда горит
		$lcd_backlight_frame->Radiobutton(-font => 'tab_rus', -text => 'Выключена', -value => '0', -variable => \$lcd_backlight,  
		-command => sub {&write_map('434','0')})->pack(-side=>'left'); #(-side => 'right');
		$lcd_backlight_frame->Radiobutton(-font => 'tab_rus', -text => 'Горит по Ситуации', -value => '1', -variable => \$lcd_backlight,  
		-command => sub {&write_map('434','1')})->pack(-side=>'left'); #(-side => 'right');
		$lcd_backlight_frame->Radiobutton(-font => 'tab_rus', -text => 'Всегда Горит', -value => '2', -variable => \$lcd_backlight,  
		-command => sub {&write_map('434','2')})->pack(-side=>'left'); #(-side => 'right');
	}
	my $acc_consrv_frame = $tab4->Frame()->pack(-side=>'top', -anchor=>'nw', -after=>$lcd_backlight_frame, -padx=>'15'); #(-side=>'top'); #tab4
	if ($lang eq 'en_US.UTF-8'){
		$acc_consrv_frame->Label(-font => 'tab_rus_bold', -text => 'Battery Conservation Mode:')
                ->pack(-side=>'left'); #(-side=>'top'); #0x1b1=433 define EE_LCD_SaveCharge     0  //Режим консервации в режиме выключенно, будет осуществлять заряд при 1
                $acc_consrv_frame->Radiobutton(-font => 'tab_rus', -text => 'Off', -value => '0', -variable => \$acc_consrv,  
                -command => sub {&write_map('433','0')})->pack(-side=>'left'); #(-side => 'right');
                $acc_consrv_frame->Radiobutton(-font => 'tab_rus', -text => 'On', -value => '1', -variable => \$acc_consrv,  
                -command => sub {&write_map('433','1')})->pack(-side=>'left'); #(-side => 'right');
	} else {
		$acc_consrv_frame->Label(-font => 'tab_rus_bold', -text => 'Консервация АКБ:')
                ->pack(-side=>'left'); #(-side=>'top'); #0x1b1=433 define EE_LCD_SaveCharge     0  //Режим консервации в режиме выключенно, будет осуществлять заряд при 1
		$acc_consrv_frame->Radiobutton(-font => 'tab_rus', -text => 'ВЫключена', -value => '0', -variable => \$acc_consrv,  
		-command => sub {&write_map('433','0')})->pack(-side=>'left'); #(-side => 'right');
		$acc_consrv_frame->Radiobutton(-font => 'tab_rus', -text => 'Включена', -value => '1', -variable => \$acc_consrv,  
		-command => sub {&write_map('433','1')})->pack(-side=>'left'); #(-side => 'right');
	}
	my $database_path_frame = $tab4->Frame()->pack(-side=>'top', -anchor=>'nw', -after=>$acc_consrv_frame, -padx=>'15'); #(-side=>'top'); #tab4
	$database_path_frame->Label(-font => 'tab_rus_small', -textvariable=>\$homedirtext )->pack(-side => 'left');

	if ($databasepath){
		if ($lang eq 'en_US.UTF-8'){
			$tab4->Button( -text=>'Delete Database', -command=>[sub{unlink($databasepath); &homedir;}] )->
                        pack(-side=>'top', -anchor=>'center', -after=>$database_path_frame, -pady=>'15');
                        $tab4->Button( -text=>'Open Folder w/Database', -command=>[sub{&browsedir($databasedir);}] )->
                        pack(-side=>'top', -anchor=>'center', -pady=>'15');
		} else {
			$tab4->Button( -text=>'Обнулить Базу', -command=>[sub{unlink($databasepath); &homedir;}] )->
			pack(-side=>'top', -anchor=>'center', -after=>$database_path_frame, -pady=>'15');
			$tab4->Button( -text=>'Открыть Папку с Базой', -command=>[sub{&browsedir($databasedir);}] )->
			pack(-side=>'top', -anchor=>'center', -pady=>'15');
		}
	}	


	if ($lang eq 'en_US.UTF-8'){
		$tab5->Label( -font => 'tab_rus_bold', -text=>'Help:' )->pack();
	} else {
		$tab5->Label( -font => 'tab_rus_bold', -text=>'Помощь:' )->pack();
	}
	my $t = $tab5->Scrolled("Text",-border=>1, -width => 85, -height=>'17', -scrollbars=> 'osoe', -background=>'lightgray')->pack(); #,-wrap=>'word',-setgrid => 'true',)->grid; 
	$t->tagConfigure('goto_url', -underline => 0, -foreground => 'black', -font => 'tab_rus');
	$t->tagConfigure('goto_url1', -underline => 1, -foreground => 'red', -font => 'tab_rus_bold');
	$t->tagConfigure('goto_url2', -underline => 0, -foreground => 'red', -font => 'tab_rus_bold');
	$t->tagConfigure('goto_url3', -underline => 1, -foreground => 'red', -font => 'tab_rus_bold');
	$t->tagConfigure('goto_url4', -underline => 0, -foreground => 'red', -font => 'tab_rus_bold');
	$t->tagConfigure('goto_url5', -underline => 1, -foreground => 'red', -font => 'tab_rus_bold');
	$t->tagConfigure('goto_url6', -underline => 0, -foreground => 'red', -font => 'tab_rus_bold');
	$t->tagConfigure('goto_url7', -underline => 1, -foreground => 'red', -font => 'tab_rus_bold');
	$t->tagConfigure('goto_url8', -underline => 0, -foreground => 'red', -font => 'tab_rus_bold');
	$t->tagConfigure('goto_url9', -underline => 0, -foreground => 'red', -font => 'tab_rus_bold');	
	$t->tagConfigure('goto_url10', -underline => 0, -foreground => 'red', -font => 'tab_rus_bold');

	if ($os =~ /Win/i){
        	eval "use Win32::FileOp qw(ShellExecute); 1" or die $@;
        	eval {
			$t->tagBind('goto_url', "<Any-Enter>", sub {$t->tagConfigure('goto_url', -relief=>'raised', -foreground => 'blue'); });
                	$t->tagBind('goto_url', "<Any-Leave>", sub {$t->tagConfigure('goto_url', -relief=>'flat', -foreground => 'black'); });
                	$t->tagBind('goto_url', "<Button-1>", sub { system("start /b http://invertor.ru")});
			$t->tagBind('goto_url1', "<Any-Enter>", sub {$t->tagConfigure('goto_url1', -relief=>'raised', -foreground => 'blue'); });
			$t->tagBind('goto_url1', "<Any-Leave>", sub {$t->tagConfigure('goto_url1', -relief=>'flat', -foreground => 'red'); });
			$t->tagBind('goto_uгl1', "<Button-1>", sub { system("start /b http://invertor.ru")});
			$t->tagBind('goto_url2', "<Any-Enter>", sub {$t->tagConfigure('goto_url2', -relief=>'raised', -foreground => 'blue'); });
			$t->tagBind('goto_url2', "<Any-Leave>", sub {$t->tagConfigure('goto_url2', -relief=>'flat', -foreground => 'red'); });
			$t->tagBind('goto_url2', "<Button-1>", sub { system("start /b http://invertor.pro")});
                	$t->tagBind('goto_url3', "<Any-Enter>", sub {$t->tagConfigure('goto_url3', -relief=>'raised', -foreground => 'blue'); });
			$t->tagBind('goto_url3', "<Any-Leave>", sub {$t->tagConfigure('goto_url3', -relief=>'flat', -foreground => 'red'); });
			$t->tagBind('goto_url3', "<Button-1>", sub { system("start /b http://инвертор.рф")});
			$t->tagBind('goto_url4', "<Any-Enter>", sub {$t->tagConfigure('goto_url4', -relief=>'raised', -foreground => 'blue'); });
			$t->tagBind('goto_url4', "<Any-Leave>", sub {$t->tagConfigure('goto_url4', -relief=>'flat', -foreground => 'red'); });
			$t->tagBind('goto_url4', "<Button-1>", sub { system("start /b http://vetrogenerator.ru")});
			$t->tagBind('goto_url5', "<Any-Enter>", sub {$t->tagConfigure('goto_url5', -relief=>'raised', -foreground => 'blue'); });
			$t->tagBind('goto_url5', "<Any-Leave>", sub {$t->tagConfigure('goto_url5', -relief=>'flat', -foreground => 'red'); });
			$t->tagBind('goto_url5', "<Button-1>", sub { system("start /b http://ветрогенератор.рф")});
			$t->tagBind('goto_url6', "<Any-Enter>", sub {$t->tagConfigure('goto_url6', -relief=>'raised', -foreground => 'blue'); });
			$t->tagBind('goto_url6', "<Any-Leave>", sub {$t->tagConfigure('goto_url6', -relief=>'flat', -foreground => 'red'); });
			$t->tagBind('goto_url6', "<Button-1>", sub { system("start /b http://stabilizator.ru")});
                        $t->tagBind('goto_url7', "<Any-Enter>", sub {$t->tagConfigure('goto_url7', -relief=>'raised', -foreground => 'blue'); });
			$t->tagBind('goto_url7', "<Any-Leave>", sub {$t->tagConfigure('goto_url7', -relief=>'flat', -foreground => 'red'); });
			$t->tagBind('goto_url7', "<Button-1>", sub { system("start /b http://microart.ru")});
                        $t->tagBind('goto_url8', "<Any-Enter>", sub {$t->tagConfigure('goto_url8', -relief=>'raised', -foreground => 'blue'); });
			$t->tagBind('goto_url8', "<Any-Leave>", sub {$t->tagConfigure('goto_url8', -relief=>'flat', -foreground => 'red'); });
			$t->tagBind('goto_url8', "<Button-1>", sub { system("start /b http://микроарт.рф")});
			$t->tagBind('goto_url9', "<Any-Enter>", sub {$t->tagConfigure('goto_url9', -relief=>'raised', -foreground => 'blue'); });
			$t->tagBind('goto_url9', "<Any-Leave>", sub {$t->tagConfigure('goto_url9', -relief=>'flat', -foreground => 'red'); });
			$t->tagBind('goto_url9', "<Button-1>", sub { system("start /b mailto:sale\@microart.ru")});

			$t->tagBind('goto_url10', "<Any-Enter>", sub {$t->tagConfigure('goto_url10', -relief=>'raised', -foreground => 'blue'); });
                        $t->tagBind('goto_url10', "<Any-Leave>", sub {$t->tagConfigure('goto_url10', -relief=>'flat', -foreground => 'red'); });
                        $t->tagBind('goto_url10', "<Button-1>", sub { system("start /b http://macenergia.com")});

        	};
	} else {
       		$t->tagBind('goto_url', "<Any-Enter>", sub {$t->tagConfigure('goto_url', -relief=>'raised', -foreground => 'blue'); });
		$t->tagBind('goto_url', "<Any-Leave>", sub {$t->tagConfigure('goto_url', -relief=>'flat', -foreground => 'black'); });
	 	$t->tagBind('goto_url', "<Button-1>", sub {system("firefox http://invertor.ru") });

		$t->tagBind('goto_url1', "<Any-Enter>", sub {$t->tagConfigure('goto_url1', -relief=>'raised', -foreground => 'blue'); });
                $t->tagBind('goto_url1', "<Any-Leave>", sub {$t->tagConfigure('goto_url1', -relief=>'flat', -foreground => 'red'); });
        	$t->tagBind('goto_url1', "<Button-1>", sub {system("firefox http://invertor.ru") });
		$t->tagBind('goto_url2', "<Any-Enter>", sub {$t->tagConfigure('goto_url2', -relief=>'raised', -foreground => 'blue'); });
                $t->tagBind('goto_url2', "<Any-Leave>", sub {$t->tagConfigure('goto_url2', -relief=>'flat', -foreground => 'red'); });
        	$t->tagBind('goto_url2', "<Button-1>", sub {system("firefox http://invertor.pro") });

		$t->tagBind('goto_url3', "<Any-Enter>", sub {$t->tagConfigure('goto_url3', -relief=>'raised', -foreground => 'blue'); });
                $t->tagBind('goto_url3', "<Any-Leave>", sub {$t->tagConfigure('goto_url3', -relief=>'flat', -foreground => 'red'); });
        	$t->tagBind('goto_url3', "<Button-1>", sub {system("firefox http://инвертор.рф") });

		$t->tagBind('goto_url4', "<Any-Enter>", sub {$t->tagConfigure('goto_url4', -relief=>'raised', -foreground => 'blue'); });
                $t->tagBind('goto_url4', "<Any-Leave>", sub {$t->tagConfigure('goto_url4', -relief=>'flat', -foreground => 'red'); });
		$t->tagBind('goto_url4', "<Button-1>", sub {system("firefox http://vetrogenerator.ru") });

		$t->tagBind('goto_url5', "<Any-Enter>", sub {$t->tagConfigure('goto_url5', -relief=>'raised', -foreground => 'blue'); });
                $t->tagBind('goto_url5', "<Any-Leave>", sub {$t->tagConfigure('goto_url5', -relief=>'flat', -foreground => 'red'); });
		$t->tagBind('goto_url5', "<Button-1>", sub {system("firefox http://ветрогенератор.рф") });

		$t->tagBind('goto_url6', "<Any-Enter>", sub {$t->tagConfigure('goto_url6', -relief=>'raised', -foreground => 'blue'); });
                $t->tagBind('goto_url6', "<Any-Leave>", sub {$t->tagConfigure('goto_url6', -relief=>'flat', -foreground => 'red'); });
		$t->tagBind('goto_url6', "<Button-1>", sub {system("firefox http://stabilizator.ru") });

		$t->tagBind('goto_url7', "<Any-Enter>", sub {$t->tagConfigure('goto_url7', -relief=>'raised', -foreground => 'blue'); });
                $t->tagBind('goto_url7', "<Any-Leave>", sub {$t->tagConfigure('goto_url7', -relief=>'flat', -foreground => 'red'); });
                $t->tagBind('goto_url7', "<Button-1>", sub {system("firefox http://microart.ru") });

		$t->tagBind('goto_url8', "<Any-Enter>", sub {$t->tagConfigure('goto_url8', -relief=>'raised', -foreground => 'blue'); });
                $t->tagBind('goto_url8', "<Any-Leave>", sub {$t->tagConfigure('goto_url8', -relief=>'flat', -foreground => 'red'); });
                $t->tagBind('goto_url8', "<Button-1>", sub {system("firefox http://микроарт.рф") });

		$t->tagBind('goto_url9', "<Any-Enter>", sub {$t->tagConfigure('goto_url9', -relief=>'raised', -foreground => 'blue'); });
                $t->tagBind('goto_url9', "<Any-Leave>", sub {$t->tagConfigure('goto_url9', -relief=>'flat', -foreground => 'red'); });
		$t->tagBind('goto_url9', "<Button-1>", sub {system("firefox mailto:sale\@microart.ru") });
	
		$t->tagBind('goto_url10', "<Any-Enter>", sub {$t->tagConfigure('goto_url10', -relief=>'raised', -foreground => 'blue'); });
                $t->tagBind('goto_url10', "<Any-Leave>", sub {$t->tagConfigure('goto_url10', -relief=>'flat', -foreground => 'red'); });
                $t->tagBind('goto_url10', "<Button-1>", sub {system("firefox http://macenergia.com") });
	}
	if ($lang eq 'en_US.UTF-8'){
		$t->insert('end', "Support, downloads, firmware, latest equipment:\n", "goto_url");
		$t->insert('end', "www.macenergia.com\n", "goto_url10");
                $t->configure(-cursor =>'hand2');
	} else {
		$t->insert('end', "Поддержка, обновления, новое оборудование:\n", "goto_url");
		$t->insert('end', "www.invertor.ru\n", "goto_url1");
		$t->insert('end', "invertor.pro\n", "goto_url2");
		$t->insert('end', "инвертор.рф\n", "goto_url3");
		$t->insert('end', "vetrogenerator.ru\n", "goto_url4");	
		$t->insert('end', "ветрогенератор.рф\n", "goto_url5");
		$t->insert('end', "stabilizator.ru\n", "goto_url6");
		$t->insert('end', "microart.ru\n", "goto_url7");
		$t->insert('end', "микроарт.рф\n", "goto_url8");
		$t->insert('end', 'Электронная почта: sale@microart.ru', "goto_url9");
		$t->configure(-cursor =>'hand2');
	}
	#$t->bind( '<Enter>', sub {$t->configure(-font => 'tab_rus_tiny'); });
	if ($lang eq 'en_US.UTF-8'){
		$tab5->Label( -font => 'tab_rus_tiny', -text=>'GNU/Artistic Licence "open source" by @pashanoid' )->pack();
                $tab5->Label( -font => 'tab_rus_tiny', -text=>'source code at http://pashanoid.ru/code/dial.pl (Perl/Tk)' )->pack();
                $tab5->Label( -font => 'tab_rus_tiny', -text=>'Usable under most known OS\'s' )->pack();
                $tab5->Label( -font => 'tab_rus_tiny', -text=>'MS Windows, all flavors of Linux, BSD & Mac' )->pack();
                $book->pageconfigure( "Sheet 5", -state=>'normal' );
                $tab5->Button( -text=>'Exit', -command=>[$tbd => 'destroy'] , -font=>'tab_rus_bold')->pack();
	} else {
		$tab5->Label( -font => 'tab_rus_tiny', -text=>'Лицензия GNU/Artistic Licence "открытый код" автор @pashanoid' )->pack();
		$tab5->Label( -font => 'tab_rus_tiny', -text=>'Исходный код на http://pashanoid.ru/code/dial.pl (Perl/Tk)' )->pack();
		$tab5->Label( -font => 'tab_rus_tiny', -text=>'Устанавливается под большинство используемых ОС' )->pack();
		$tab5->Label( -font => 'tab_rus_tiny', -text=>'Все семейства Windows, Linux, BSD и Mac' )->pack();
		$book->pageconfigure( "Sheet 5", -state=>'normal' );
		$tab5->Button( -text=>'Выход', -command=>[$tbd => 'destroy'] , -font=>'tab_rus_bold')->pack();
	}
}

sub chart{
	my $chart_period = shift;
	#print "chart type=$chart_type\n";
	$minid = 1; #initial minid!
	$maxid = "";
	return if ($chart_period == 1); 		#do nothing
	return if Exists($mwc); 			#only one chart allowed
	my ($chart_period_back);
	my ($d, $e) = (0.00001, 1);			#show 100% of $chart_period_type
	($chart_period_back) = &update_data($chart_period, $d, $e);
	drawcharts($chart_period);
	return;
}

sub drawcharts {
	my $chart_period = shift;
	my ($x_begin, $y_begin);
        
	$font_counter_ch++;
        $mwc = $mw -> Toplevel();
	$mwc->Icon(-image => $ico);
        #$mwc->geometry( "750x970" );
        $mwc->geometry( "750x800");
        $mwc->optionAdd("*font", "*utf-8");
	if ($lang eq 'en_US.UTF-8'){
		$mwc->title('MAC Voltage: V in, V out');
	} else {
	        $mwc->title('Входное и Выходное напряжение МАП: U in, U out');
        }
	$mwc->optionAdd("*font", "*utf-8");
        $mwc->fontCreate('giant_rus', -family => 'nimbus sans l', -weight => 'normal', -size=>int(-13*13/10)) unless ($font_counter_ch >1);
        $mwc->fontCreate('tiny_rus', -family => 'nimbus sans l', -weight => 'normal', -size=>int(-12*12/10)) unless ($font_counter_ch >1);
	if ($lang eq 'en_US.UTF-8'){
		$chart_exit = $mwc->Button( -text=>'Exit', -command=>[ $mwc => 'destroy'] )->pack(-padx=>15, -pady=>15, -anchor=>'nw', -side=>'bottom');
	} else {
		$chart_exit = $mwc->Button( -text=>'Закрыть', -command=>[ $mwc => 'destroy'] )->pack(-padx=>15, -pady=>15, -anchor=>'nw', -side=>'bottom');
	}
	#$lcd_backlight_frame->Label(-font => 'tab_rus_bold', -text => 'Подсветка ЖКИ:')->pack(-side=>'left');
	#$database_path_text = $mwc->Label(-font => 'tab_rus', -textvariable=>\$homedirtext )->pack(-padx=>25, -pady=>15, -anchor=>'nw', -side => 'bottom', -after=>$chart_exit);
	&set_charts;

        $chart->plot(\@data);
        $chart2->plot(\@data2);
	$chart3->plot(\@data3);
        $chart_exit->raise($chart3);
	#$database_path_text->raise($chart3);
	
        $mwc->bind('<ButtonPress>' => sub { 
        	$mwc->configure(-cursor => 'crosshair');
                $x_begin = $Tk::event->x;
                $y_begin = $Tk::event->y; #needed for charting the rectangle
                $mwc->bind('<Motion>' => sub { 
				$mwc->configure(-cursor => 'bottom_right_corner');
        			my $x_now = $Tk::event->x;
        			my $y_now = $Tk::event->y;
        			$chart->createRectangle($x_begin, $y_begin, $x_now, $y_now, -width => 1, -outline => 'yellow', -tag=>'yellow');
        			$chart2->createRectangle($x_begin, $y_begin, $x_now, $y_now, -width => 1, -outline => 'orange', -tag=>'orange');
				$chart3->createRectangle($x_begin, $y_begin, $x_now, $y_now, -width => 1, -outline => 'green', -tag=>'green');
			 });
        	});
        my $x_now;
	$mwc->bind('<ButtonRelease>' => sub {
			my $x_now = $Tk::event->x;
                        $mwc->bind('<Motion>', "");
                        my $chart_width = ($chart->width); #100 pixels for margins at beginning/end of chart
                        $chart->delete('yellow');
                        $chart2->delete('orange');
			$chart3->delete('red');
                        my $del = $chart_width-100;
                        $del = 0.00001 if ($del <= 0);
                        my $d = ($x_begin-100)/$del;
                        $d = 0.00001 if ($d < 0);
                        $d = 100 if ($d > 100);
                        $x_now = 0 unless ($x_now);
                        my $e = ($x_now-100)/$del;
                        $e = 0.00001 if ($e < 0);
                        $e = 100 if ($e > 100);
                        $chart->clearchart;
                        $chart2->clearchart;
			$chart3->clearchart;
                        $chart->destroy;
                        $chart2->destroy;
			$chart3->destroy;
                        $mwc->destroy;
                        &update_data($chart_period, $d, $e);
                        &drawcharts($chart_period);
		} );
}



if ($disconnected){
	&disconnect;
	exit;
} 
#else {	&connect;}
#$mw -> repeat(7500, sub{&readings});
$mw -> repeat(7000, sub{readings()});

MainLoop;

sub browsedir {
	my $databasedir = shift;
	if ($^O eq 'MSWin32') {
		eval "use Win32::FileOp qw(ShellExecute); 1" or die $@;
                eval { system("start explorer /e,\"$databasedir\""); };
                #eval { system("Explorer");};
    		#exec "start $databasedir";
  	} else {
    		system ("nautilus $databasedir");
	}
}



sub homedir {

        my $homedir = File::HomeDir-> my_dist_data('mapenergy');
        File::HomeDir->my_dist_data('mapenergy', { create => 1 }) unless ($homedir); #print "created $homedir\n";
        $homedir = File::HomeDir-> my_dist_data('mapenergy'); #print "read homedir = $homedir\n";
        my $configuration_file = $homedir.'/map.cfg';
        my $cfg = new Config::Simple($configuration_file); #read the config file
        unless ($cfg){
                $cfg= new Config::Simple(syntax=>'ini');
                $cfg->param("sqlite.dsn", "---");
                $cfg->param("corporate", "microart");
                $cfg->param("author", '@pashanoid');
                $cfg->param("site.title", 'MAC ENERGY SINE Monitoring and Configuration');
		$cfg->param("lang",'ru_RU.UTF-8');
		if ($qty){
			$cfg->param("qty", $qty);
		} else {
			$cfg->param("qty", '1');
		}
                $cfg->write($configuration_file);
        }
        $cfg->import_names(); #print Dumper($cfg);
	#my $lc = File::HomeDir->my_dist_data( 'lc' );
	$lang = $cfg->param('lang');
	$qty = $cfg->param('qty');
	#print "lang=$lang\n";
	

	my $dbfile = $homedir.'/sqlite.db';
	my $filesize;
	$os = $^O;
	if ($os =~ /Win/i){
		$databasedir = $homedir;
		$databasepath = $homedir.'\sqlite.db'; 
		$filesize = format_bytes(-s $databasepath); # 4.5M
		if ($lang eq 'en_US.UTF-8'){
			$homedirtext = 'Database: '.$homedir.'\sqlite.db'. " : (Size: $filesize)";
		} else {
			$homedirtext = 'База данных: '.$homedir.'\sqlite.db'. " (Размер: $filesize)";	
		}
	} else {
		$databasedir = $homedir;
		$databasepath = $homedir.'/sqlite.db';
		$filesize = format_bytes(-s $databasepath); # 4.5M
		if ($lang eq 'en_US.UTF-8'){
			$homedirtext = 'Database: '.$dbfile. " (Size: $filesize)";
		} else {
			$homedirtext = 'База данных: '.$dbfile. " (Размер: $filesize)";
		}
	}
	my $dbh = DBI->connect("dbi:SQLite:dbname=$dbfile","","");
	my $exists;
	my $sth = $dbh->table_info(undef, '%', 'maplog' , "TABLE");
	$sth->execute();
        while (my @result = $sth->fetchrow_array()) {	
		$exists = $result[3];
	}
	$exists = "" unless ($exists);
	$sth->finish;
	unless ($exists eq 'TABLE') { #table does not exist
                $dbh->do("CREATE TABLE maplog (
                        id INTEGER PRIMARY KEY AUTOINCREMENT,
                        count INTEGER, date DATE,
                        status_map INTEGER, status_acc INTEGER,
                        v_acc INTEGER, v_in INTEGER, v_out INTEGER, 
                        power INTEGER, current_acc INTEGER, current_net INTEGER, freq INTEGER,
                        t_acc INTEGER, t_tor INTEGER, t_trans INTEGER
                        )"
                );
		$dbh->do("CREATE TABLE maperr (
			id INTEGER PRIMARY KEY AUTOINCREMENT,
			date DATE,
			errtype INTEGER,
			errnum INTEGER,
			errhuman VARCHAR(200)
			)"
		);

	}
	$dbh->disconnect;
        return ($configuration_file, $homedir, $dbfile, $lang);
}
sub set_charts{

	my $title;
	my @legends;
	if ($lang eq 'en_US.UTF-8'){
		$title = 'MAC Voltages: V in & V out';
		@legends = ( 'V in', 'V out' );
	} else {
		$title = '   U вх/вых',
		@legends = ( 'U вх', 'U вых' );
	}

	$chart = $mwc->Lines(
        	-title  => $title,
        	-titlefont => 'giant_rus',
		-titleheight => '20',
		-textfont => 'tiny_rus',
        	-xlabelfont => 'tiny_rus',
        	-ylabelfont => 'tiny_rus',
        	-boxaxis => 1,
        	-yticknumber => 5,
        	-linewidth => 2,
        	-bezier => 1,
        	-alltickview => 1,
        	-pointline => 0,
        	-markers => [10, 9, 9],
        	-xtickheight => 5,
        	-ylongticks => 1,
        	-ylongtickscolor => 'white',
        	-xlongticks => 1,
        	-xlongtickscolor => 'white',
        	-width => 800,
        	-height => 250,
        	-yminvalue => 0,
        	-ymaxvalue => 260,
        	-xlabelskip => $xlabelskip,
	)->pack(qw / -fill both -expand 1/);
	$chart->enabled_gradientcolor();
	$chart->set_gradientcolor(
        	-start_color => '#bdbebe',
        	-end_color   => '#aed5e2',
        	-type => 'linear_vertical',
	);

	@legends = ( 'U вх', 'U вых' );
  	$chart->set_legend(
    		-title		=> $title,
    		-data		=> \@legends,
    		-titlecolors	=> 'blue',
		-titlefont	=>'tiny_rus',
		-legendfont	=>'tiny_rus'
  	);
	$chart->set_balloon();
	
	if ($lang eq 'en_US.UTF-8'){
                $title = '   V batt.';
                @legends = ( 'V batt.' );
        } else {
                $title = '   U акб',
                @legends = ( 'U акб' );
        }

	$chart2 = $mwc->Lines(
        	-title  => $title,
        	-titlefont => 'giant_rus',
		-textfont => 'tiny_rus',
        	-titleheight => '5',
		-xlabelfont => 'tiny_rus',
        	-ylabelfont => 'tiny_rus',
        	-boxaxis => 1,
        	-yticknumber => 5,
        	-linewidth => 2,
        	-bezier => 1,
        	-alltickview => 1,
        	-pointline => 0,
        	-markers => [10, 9, 9],
        	-xtickheight => 5,
        	-ylongticks => 1,
        	-ylongtickscolor => 'white',
        	-xlongticks => 1,
        	-xlongtickscolor => 'white',
        	-width => 800,
        	-height => 250,
        	-yminvalue => 9*$qty,
        	-ymaxvalue =>17*$qty,
        	-xlabelskip => $xlabelskip,
	)->pack(qw / -fill both -expand 1 /);

	$chart2->enabled_gradientcolor();
	$chart2->set_gradientcolor(
        	-start_color => '#bdbebe',
        	-end_color   => '#aed5e2',
        	-type => 'linear_vertical',
	);
        #$chart2->set_legend(
        
	#        -title          => 'Графики напряжения АКБ',
        #        -data           н=> \@legends2,
        #        -titlecolors    => 'blue',
        #        -titlefont	=>'tiny_rus',
	#	-legendfont     =>'tiny_rus'
        #);
        #$chart2->set_balloon();

	my $chart3_title = '   P мощность (кВт)';
	$chart3_title = '   P power (kWt)' if ($lang eq 'en_US.UTF-8');
	my $chart3_yminvalue = $map_power*(-1);
	my $chart3_ymaxvalue = $map_power;
	if ($chart_type eq 'i'){
		$chart3_title =	'   I ток (А)';
		$chart3_title = '   I current (A)' if ($lang eq 'en_US.UTF-8');
		$chart3_yminvalue = $map_current_max*(-1);
		$chart3_ymaxvalue = $map_current_max;	
	} 

	$chart3 = $mwc->Lines(
                -title  => $chart3_title,
                -titlefont => 'giant_rus',
                -textfont => 'tiny_rus',
		-titleheight => '5',
                -xlabelfont => 'tiny_rus',
                -ylabelfont => 'tiny_rus',
                -boxaxis => 1,
                -yticknumber => 5,
                -linewidth => 2,
                -bezier => 1,
                -alltickview => 1,
                -pointline => 0,
                -markers => [10, 9, 9],
                -xtickheight => 5,
                -ylongticks => 1,
                -ylongtickscolor => 'white',
                -xlongticks => 1,
                -xlongtickscolor => 'white',
                -width => 800,
                -height => 250,
                -yminvalue => $chart3_yminvalue,
                -ymaxvalue => $chart3_ymaxvalue,
                -xlabelskip => $xlabelskip,
		-zeroaxisonly => 1,
        )->pack(qw / -fill both -expand 1 /);
        $chart3->enabled_gradientcolor();
        $chart3->set_gradientcolor(
                -start_color => '#bdbebe',
                -end_color   => '#aed5e2',
                -type => 'linear_vertical',
        );

	#print "map_power=$map_power\n";
	
	my $zoomtext = $chart->createText(5, 5, -text=> $zoomsign, -font=>'giant_rus', -anchor => 'nw', -tag => 'zoom');
	#my $zoomtext = $chart->createText(-text=> $zoomsign, -font=>'giant_rus', -tag => 'zoom')->pack(-anchor=>'nw', -side=>'bottom', -padx=>'15', -pady=>'15');
}
sub update_data{
	my ($chart_period, $d, $e) = @_;
	my $c;
	if ($e < $d){
		$c = $e;
		$e = $d;
		$d = $c;
	}
	

	my @timeline = (); my @v_in =(); my @v_out =(); my @v_acc =(); my @power = (); my @current =(); 
        my $dbfile = $homedir.'/sqlite.db';
        my $dbh = DBI->connect("dbi:SQLite:dbname=$dbfile","",""); #
        my $sth;
        my $date;
        
	unless ($maxid){ #if not max id has been set so far!
        	$sth = $dbh->prepare("SELECT max(id) from maplog;");
         	$sth->execute();
         	while (my @result = $sth->fetchrow_array()) {
         		$maxid = $result[0];
         	}
                $sth->finish;
        }
        my $maxdate; #max recorded date in database
        $sth = $dbh->prepare("SELECT max(strftime('%s',date)) FROM maplog;");
                $sth->execute();
                while (my @result = $sth->fetchrow_array()) {
                        $maxdate = $result[0];
                }
        $sth->finish;
	$maxid = 0 unless ($maxid);
	$minid = 0 unless ($minid);
        my $interval = ($maxid - $minid); #dates shown in chart line
	$maxid = int($minid+$interval*$e);
        $minid = int($minid+$interval*$d);
        if ($chart_period == 2){ #one day
                $date = $maxdate - 3600*24;
        } elsif ($chart_period == 3){ #one week
                $date = $maxdate - 3600*24*7;
        } elsif ($chart_period == 4){ #one month
                $date = $maxdate - 3600*24*7*4;
        } elsif ($chart_period == 5){
                $date = $maxdate - 3600*24*7*4*6; #six months
        } elsif ($chart_period == 6){
                $date = $maxdate; #all
        } else { #one hour ago
                $date = $maxdate - 3600;
        }
        $date = &convert_dates($date);
        my $period_phrase = "(date > \'$date\')"; #print "period_phrase=$period_phrase\n";
	my $period_begin_id = "";
        $sth = $dbh->prepare("SELECT min(id) FROM maplog WHERE $period_phrase;");
                $sth->execute();
                while (my @result = $sth->fetchrow_array()) {
                        $period_begin_id = $result[0];
                }
        $sth->finish; #print "period_begin_id = $period_begin_id\n";
        $period_begin_id = 0 unless ($period_begin_id);
	$minid = $period_begin_id if ($period_begin_id > $minid); #print "minid=$minid\n";
        my $phrase = "SELECT strftime(\'%H:%M:%SN%d\.%m\',date), v_in, v_out, v_acc, power, status_map, current_acc, current_net 
		FROM maplog WHERE ((id > \'$minid\') and (id < \'$maxid\'))";
	#my $phrase = "SELECT id, v_in, v_out, v_acc  FROM maplog WHERE ((id > \'$minid\') and (id < \'$maxid\'))";
       	#print "phrase=$phrase\n";
	$sth = $dbh->prepare($phrase);
        $sth->execute();
        my $count = 0;
	my $datetextit = "";
        while (my @result = $sth->fetchrow_array()) {
                $datetextit = $result[0];
		next unless ($datetextit);
		$datetextit =~ s/N/\n  /g;
                push (@timeline, $datetextit);
                push (@v_in, $result[1]);
                push (@v_out, $result[2]);
                push (@v_acc, $result[3]);
		if ($result[5] != 3) { #status map
			push (@power, ($result[4]*(-1))); #negative value when on acc!
			push (@current, ($result[6]*(-1))); #negative current when on acc!
		} else { #we're using the grid!
			push (@power, $result[4]);
			push (@current, $result[7]);
		} 
		$count++;
        }
        if ($count == 0){
                ($d, $e, $minid, $maxid) = (0.00001, 1, '','');
		&update_data($chart_period, $d, $e); #update self with same periods w/o zoom!
                return;
        }
        $sth->finish;
        $dbh->disconnect;
        if ($count < 10){
                for (my $i=0; $i<10; $i++){
                        if (!$timeline[$i]){ #last timeline tick
                                $timeline[$i]=$timeline[$i-1];
                                $v_in[$i]=$v_in[$i-1];
                                $v_out[$i]=$v_out[$i-1];
                                $v_acc[$i]=$v_acc[$i-1];
				$power[$i-1] = 0 unless ($power[$i-1]);
				$power[$i]=$power[$i-1];
				$current[$i]=$current[$i-1];
                        }
                }
        }



        $xlabelskip = int($count/10);
        $xlabelskip = 1 if ($xlabelskip < 1);
        if ($old_interval){
                $zoom = int(100 - 100*($interval/$old_interval));
		$zoom = 0 if ($zoom <0);
	$zoomsign = 'масштаб: '.$zoom.'%';
                $zoomsign = '*график растягивается, увеличивать масштаб можно левой клавишей мышки' if ($zoom == 0);
        }
	$old_interval = $interval;
        $zoomsign = '*график растягивается, увеличивать масштаб можно левой клавишей мышки' unless ($zoom);
        if ($lang eq 'en_US.UTF-8'){
		$zoomsign = '';

	}
	@data = (\@timeline, \@v_in, \@v_out);
	@data2 = (\@timeline, \@v_acc);
	if ($chart_type eq 'p'){
		@data3 = (\@timeline, \@power);
	} else {
		@data3 = (\@timeline, \@current);
	}
	return($chart_period);
}

sub convert_dates{
        my $date = shift;
        #my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($date);
	my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime($date);
        $year += 1900;
        $sec = sprintf("%02d", $sec);
        $min = sprintf("%02d", $min);
        $hour = sprintf("%02d", $hour);
	$mday = sprintf("%02d", $mday);
        $mon = sprintf("%02d", $mon+1);
        my $sqlite_date = "$year-$mon-$mday $hour:$min:$sec"; #SQLite date old->#my $sqlite_date = "$mday/$mon/$year $hour:$min:$sec";
        return($sqlite_date);
}


sub write_charge_time{
	my ($mem, $value) = @_;
        return if ($value eq "-");
        #$value = int($value*60/16); #because
        $value = sprintf("%01d", ($value*60/16));
        &writemap($mem, $value);
}

sub write_net_type{
        my ($mem, $value) = @_;
        return if ($value eq "-");
        $value = $value*10; #because
        &writemap($mem, $value);
}


sub write_capacity{
	my ($mem, $capacity) = @_;
        return if ($capacity eq "-");
        $capacity = $capacity/10; #because
        &writemap($mem, $capacity);
}

sub write_current{
        my ($mem, $current) = @_;
        return if ($current eq "-");
        $current = $current*100; #because
        &writemap($mem, $current);
}

sub write_voltage_acc{
        my ($mem, $voltage) = @_;
        return if ($voltage eq "-");
	$qty = 1 unless ($qty);
        $voltage = $voltage*10/$qty; #because acc_voltage is stored in 12v*$qty (quantifyer = 1, 2, 4);
        &writemap($mem, $voltage);
}

sub write_voltage{
	my ($mem, $voltage) = @_;
	return if ($voltage eq "-");
	$voltage = $voltage-100; #because
	&writemap($mem, $voltage);
}

sub write_time{
	my ($mem, $hours, $mins) =@_;
	return if ($hours eq "-");
	return if ($mins eq "-");
	$hours = int($hours);
	$mins = int($mins);
	$hours = 0 if (!$hours);
	$mins = 0 if (!$mins);


	my $hours_bin = unpack("B32", pack("N", $hours)); #hours in binary
        #$hours_bin =~ s/^0+(?=\d)//;   # otherwise you'll get leading zeros
	$hours_bin = sprintf("%05d", $hours_bin); #5 bits
	
	$mins = $mins/10;
        my $mins_bin = unpack("B32", pack("N", $mins)); #minutes in binary
	$mins_bin = sprintf("%03d", $mins_bin);   #3 bits
	my $entire_byte = "$hours_bin"."$mins_bin";
	my $dec = unpack("N", pack("B32", substr("0" x 32 . $entire_byte, -32))); #to dec
	#print "mem=$mem hour=$hours mins=$mins hours_bin=$hours_bin mins_bin=$mins_bin entire_byte=$entire_byte dec=$dec\n";
	&writemap($mem, $dec);
}

sub write_map{
        my ($name,$value) = @_; #print "writting to map $name => $value\n"; #addr 0x138 = 312 //0 - Чистый Sin 5%, 1- Оптимальный Sin 5% до 200В, 2 -Pmx Sin 20%
	&writemap($name, $value);

	#initiate values!
	&writemap(0,7);
}



sub readings{
	exit if ($disconnected);
	#my ($coords_x, $coords_y) = $mw->pointerxy;
	#$c->itemconfigure($coords_curs,-text => "x=$coords_x y=$coords_y");

	
	$logcount++;
	$logcount = 1 if ($logcount == 0);	
	$logcount = 1 if ($logcount > 2);
	$log{$logcount}{'count'}++;
	#$testcount ++;

	my $colorfill;
	my $mem; #delete afterwards!
	my $answer = "";
	my $value;
	my ($acc_type_text, $capacity_entire_text);
	my ($bs, $times_map, $addr1033, $socket_voltage_in, $addr1060, $freq_on_socket, $freq_on_acc, $u_socket_out);
	my ($current_acc, $current_net) = (0,0);
	my $status_acc=0;
	my ($err1066, $err1067, $err1068, $err1069, $addr1070, $addr1071, $addr1072);

	$map_operation = 33;
	@mapcommand =('P', 'C', 'P', 'R', '4', '0', '0', '6', 'C', "\r", "\n");
	my ($ans1, $ans2) = (0,0);
	($map_operation, $bs, $bs, $bs, $acc_status, $ans1, $ans2, $bs,
        $current_acc, $addr1033, $bs, $bs, $bs, $bs, $bs, $bs) = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
	($map_operation, $bs, $bs, $bs, $acc_status, $ans1, $ans2, $bs,
	$current_acc, $addr1033, $bs, $bs, $bs, $bs, $acc_discharged, $bs) = readmappage('1024') unless ($port_not_opening); #last is 1039

	#print "logcount = $logcount\n";
	#print "acc_discharged = $acc_discharged testcount=$testcount\n";
	#$acc_discharged = 50 if ($testcount > 5);
	#print "Turn GRID off and I will -- Shutdown NOW!" if ($testcount > 5);
	
	if ($port_not_opening) { #ячейка 1024; #Режим работы мап
		$reading = "Нет соединения с МАП-ом ($port_not_opening)";
		$answer = 33;
		$colorfill = 'orangered2';
	} else { #port is ok
		#$answer = int(readmap('1024')); #Режим работы мап
		if ($map_operation == 3 || $map_operation == 4){ #w/grid!
			$colorfill = '#10f0f0';
			#$map_operation = 3;
			&shutdownabort if (($acc_discharged > 55) && ($count_shutdown > 0)); #stop shutdown!
		} else { #batt_power!
			$colorfill = '#48f878';
			#$map_operation = $answer;
			#print "Shutdown NOW!" if ($testcount > 5);
			&shutdown if ($acc_discharged < 55); #on batt power
		}
	}
	$c->itemconfigure($status_map, -text => "$MapStatuses{$lang}{$map_operation}", -fill=>$colorfill);
	$log{$logcount}{'status_map'} = $map_operation;


	&connect if ($map_operation == 33);

	unless ($port_not_opening){
		$current_acc = $current_acc*2;
		$log{$logcount}{'current_acc'} = $current_acc;
	}
	

	unless ($port_not_opening) {
        	$log{$logcount}{'status_acc'} = $acc_status;
		$Cacc = 100*$acc_status/3; #4-100% 4=100 a=x x=100*a/4
        	$Cacc = $Cacc - 10 if ($log{$logcount}{'status_map'} == 4);
        	$Cacc = sprintf("%.0f", $Cacc);
		if ($lang eq 'en_US.UTF-8'){
			$Cacc_text = 'Batt. state: '.$EnStateUAcc{$lang}{$acc_status}.' '.$Cacc.'%';
		} else {
			$Cacc_text = 'Состояне АКБ: '.$EnStateUAcc{$lang}{$acc_status}.' '.$Cacc.'%';
		}		
	} else {
		if ($lang eq 'en_US.UTF-8'){
			$Cacc_text = 'Batt. state: n/a ';
		} else {
			$Cacc_text = 'Состояне АКБ: н/д ';	
		}
	}
	my $pos = 90; #initially down
	$answer = 0;
	#($ans1, $ans2)= (0,0);
	if ($port_not_opening) { 
		$reading = 0;
		$answer = 0;
		$pos = 0; # (90-9*$qty)/6; #hand down
	} else {
		#my ($ans1, $ans2)= (0,0);
        	#$ans1 = int(readmap('1029')) unless ($port_not_opening); #v_acc -- _St_UAcc_med_VH;
        	#$ans2 = int(readmap('1030')) unless ($port_not_opening);
	       	$answer = ($ans1*256 + $ans2)/10;
		$qty = 1 if (!$qty);
		$pos = ($answer/$qty-9)/6; #what % is $answer of 6 tick scale
	}
	my $x = 166 - 100.0 * (cos( $pos * PI )); #was 100 -90*
        my $y = 250 - 100.0 * (sin( $pos * PI ));
        $c->coords('needle1', 166, 250, $x, $y);
	if ($lang eq 'en_US.UTF-8'){
		$reading = sprintf("%.1fV", $answer);	
	} else {
		$reading = sprintf("%.1f В ", $answer);
	}
	$c->itemconfigure($voltage_acc_text,-text => $reading);
        $log{$logcount}{'v_acc'} = $answer;

	($socket_voltage_in, $current_net, $addr1060, $freq_on_socket, $freq_on_acc, $u_socket_out, $bs, $bs,
        $err1066, $err1067, $err1068, $err1069, $addr1070, $addr1071, $addr1072, $bs) = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
	($socket_voltage_in, $current_net, $addr1060, $freq_on_socket, $freq_on_acc, $u_socket_out, $bs, $bs, 
	$err1066, $err1067, $err1068, $err1069, $addr1070, $addr1071, $addr1072, $bs) = readmappage('1058') unless ($port_not_opening); #1058-1073
	#print "port_not_opening=$port_not_opening\n";
	
	@mapcommand =('P', 'C', 'R', 'D', '4', '0', '0', '6', 'C', "\r", "\n"); #back to default


	unless ($port_not_opening){
                $current_net = $current_net;
                $log{$logcount}{'current_net'} = $current_net;
        }

	# Показываем напряжение входной розетки
        #$mem = 1058; #"Напряжение входной розетки - данные от SPI: ";
        #$answer = &readmap($mem) unless ($port_not_opening);
        $socket_voltage_in = 0 if ($port_not_opening); #no connection!
        $socket_voltage_in += 100 unless ($socket_voltage_in == 0);
	if ($lang eq 'en_US.UTF-8') {
		$reading = sprintf("%.0fV", $socket_voltage_in);
	} else {
        	$reading = sprintf("%.0f В", $socket_voltage_in);
	}
        $c->itemconfigure($status_volt_in,-text => $reading, -fill=>$colorfill);
        $log{$logcount}{'v_in'} = $socket_voltage_in;	

	#$mem = 1061; # freq  #read 1062 when on acc!
        if ($map_operation == 3 || $map_operation == 4){
		$answer = $freq_on_socket;
	} else {
		$answer = $freq_on_acc;
	}
	if ($port_not_opening) {
		if ($lang eq 'en_US.UTF-8') {
			$reading = 'n/a';
		} else {
			$reading = 'н/д';
		}
	} else {
		if ($lang eq 'en_US.UTF-8') {
			$reading = sprintf("%.0f Hz", $answer);
		} else {
			$reading = sprintf("%.0f Гц", $answer);
		}
	}
        $c->itemconfigure($status_freq,-text => $reading, -fill=>$colorfill);
        $log{$logcount}{'freq'} = $answer;

	unless ($port_not_opening){
		$answer = $u_socket_out + 100;
	} else { 
		$answer = 0; #no connection!
	}
	$answer = 190 if ($answer == 0);	
	$pos = (($answer-190)/6)/10; #print "1063 = $pos\n"; #print "answer=$answer pos=$pos\n";
	$x = 475 - 90.0 * (cos( $pos * PI )); #was 100 -90*
        $y = 250 - 90.0 * (sin( $pos * PI ));
	$c->coords('needle2', 475, 250, $x, $y);
	$answer = 0 if ($port_not_opening); #no connection!
	if ($lang eq 'en_US.UTF-8') { 
		$reading = sprintf("%.0fV", $answer);
	} else {
		$reading = sprintf("%.0fВ", $answer);
	}
        $c->itemconfigure($voltage_socket_out_text,-text => $reading);
	$log{$logcount}{'v_out'} = $answer;

	$answer = $addr1070 - 50;
	unless ($port_not_opening){
		$answer = $addr1070 - 50;
		$reading = sprintf("%.0f°C", $answer);
		$temp_batt = $answer;
		if ($lang eq 'en_US.UTF-8') {
			$temp_batt_text = 'Batt. temp.: '. $reading;	
		} else {
			$temp_batt_text = 'Температура АКБ: '. $reading;
		}
		$log{$logcount}{'t_acc'} = $answer;
	} else {
		if ($lang eq 'en_US.UTF-8') {
			$reading = 'n/a';
		} else {
			$reading = 'н/д';
		}
	}
	$c->itemconfigure($status_batt_text,-text => $reading, -fill=>$colorfill);

	unless ($port_not_opening){
		$temp_transistors_text = sprintf("%.0f°C", ($addr1071 - 50));
		$log{$logcount}{'t_trans'} = $temp_transistors_text;
	} else {
		if ($lang eq 'en_US.UTF-8') {
			$temp_transistors_text = 'n/a';
		} else {
			$temp_transistors_text = 'н/д';
		}
	}
	$c->itemconfigure($temp_transistors_sign, -text => $temp_transistors_text, -fill=>$colorfill);

	unless ($port_not_opening){
		$temp_tor_text = sprintf("%.0f °C", ($addr1072 - 50));	
		$log{$logcount}{'t_tor'} = $temp_tor_text;
	} else {
		if ($lang eq 'en_US.UTF-8') {
			$temp_tor_text = 'n/a';
		} else {
			$temp_tor_text = 'н/д';
		}
	}
	$c->itemconfigure($temp_tor_sign, -text => $temp_tor_text, -fill=>$colorfill);

	@mapcommand =('P', 'C', 'P', 'R', '4', '0', '0', '6', 'C', "\r", "\n");

	($acc_type, $capacity_entire, $current_start_charge, $current_end_charge, $charge_alg, $map_acc_charge_end, $map_acc_sust_charge, $map_acc_charge_start,
                $bs, $bs, $bs, $bs, $bs, $bs, $bs, $bs) = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
	($acc_type, $capacity_entire, $current_start_charge, $current_end_charge, $charge_alg, $map_acc_charge_end, $map_acc_sust_charge, $map_acc_charge_start,
		$bs, $bs, $bs, $bs, $bs, $bs, $bs, $bs) = readmappage('384') unless ($port_not_opening);
	#my %batt_types = ('0' => 'Кислотный Рег', 1 => 'Гелевый/AGM T', 2 => 'Кислотный T', 3 => 'Щелочной', );

	if ($port_not_opening){
		if ($lang eq 'en_US.UTF-8') {
			$acc_type_text = 'n/a';
		} else {
			$acc_type_text = 'н/д';
		}
	} else {
		$acc_type_text = $batt_types{$lang}{$acc_type};
	}
	$c->itemconfigure($status_batt_type_text,-text => $acc_type_text, -fill=>$colorfill);

	if ($port_not_opening){
		if ($lang eq 'en_US.UTF-8') {
			$capacity_entire_text = 'n/a';
		} else {
			$capacity_entire_text = 'н/д';
		}
	} else {
		$capacity_entire = $capacity_entire*10;
		if ($lang eq 'en_US.UTF-8') {
			$capacity_entire_text = sprintf("%.0f Ah", $capacity_entire);
                        $capacity_entire_text = $capacity_entire_text .'* '. ($qty*12).'Vdc';
		} else {	
			$capacity_entire_text = sprintf("%.0f Ач", $capacity_entire);
			$capacity_entire_text = $capacity_entire_text .'* '. ($qty*12).'В';
		}
	}
	$c->itemconfigure($status_batt_text,-text => $capacity_entire_text, -fill=>$colorfill);
	$current_start_charge = $current_start_charge/100;
	$current_end_charge = $current_end_charge/100;
	$map_acc_charge_end = sprintf("%.1f", (($map_acc_charge_end/10)*$qty));
	$map_acc_sust_charge = sprintf("%.1f", (($map_acc_sust_charge/10)*$qty));
	$map_acc_charge_start = sprintf("%.1f", (($map_acc_charge_start/10)*$qty));
	@mapcommand =('P', 'C', 'R', 'D', '4', '0', '0', '6', 'C', "\r", "\n"); #back to default

	$mem = 0;
	$addr1033 = 0 unless ($addr1033);
	$mem = int($addr1033);
	$mem = 0 unless ($addr1033);
	if ($lang eq 'en_US.UTF-8') {
		$reading = 'Batt. output power: '; 
	} else {
		$reading = 'Мощность по АКБ: ';
	}
	if (($map_operation == 3) || ($map_operation == 4)){ #net
		$mem = int($addr1060); #map power net
		$mem = 0 unless ($addr1060);
		if ($lang eq 'en_US.UTF-8') {
			$reading = 'Grid output power: ';
		} else {
			$reading = 'Мощность по сети: ';
		}
	} 
	$log{$logcount}{'date'} = &timestamp;
	$log{$logcount}{'power'} = 0;
	unless ($port_not_opening) {
		$answer = $mem/10; #power
		$powermeter = $answer*100; #for chart!
	
		#print "power=$powermeter\n";
	
		$power_text = $reading.sprintf("%.1f kW", $answer);
		$c->itemconfigure($power_text,-text => $reading, -fill=>$colorfill);
		$log{$logcount}{'power'} = $answer;
		my $errnum = '';

		$answer= $err1069;  #1024+45 (AddrMem+_St_RSWarning);
		#print "1069=$answer\n";
		for (my $i=1; $i<256; $i=$i*2) {
        		if (($answer&$i)!=0) {
				$timestamp = &timestamp;
				$errnum = ($answer&$i);
				$warnings = "$EnWarning{$errnum}";
				#$prompt_warning->Show();
				
				#my $dbh = DBI->connect("dbi:SQLite:dbname=$dbfile","","");
                		#$dbh->do("INSERT INTO maperr 
                        	#(date, errtype, errnum, errhuman)
                        	#	VALUES (?,?,?,?)", undef, 
				#	"$timestamp", '1069', "$errnum", "$warnings"	
                		#);
               			#$dbh->disconnect;
			} 
			
		}
		$err1069 = 0;
		if ($answer==0) {
			$warnings = 'теперь всё ок!';
			#$prompt_warning->Exit;
		}

                $answer= $err1066;  #1024+42 (AddrMem+_St_RSWarning);
                for (my $i=1; $i<256; $i=$i*2) {
                        if (($answer&$i)!=0) {
				$timestamp = &timestamp;
				$errnum = ($answer&$i);
                                $errors = "$EnErrSis{$errnum}";
                        	#my $dbh = DBI->connect("dbi:SQLite:dbname=$dbfile","","");
                                #$dbh->do("INSERT INTO maperr 
                                #(date, errtype, errnum, errhuman)
                                #        VALUES (?,?,?,?)", undef, 
                                #        "$timestamp", '1066', "$errnum", "$errors"
                                #);      
                                #$dbh->disconnect;
			} 
                }
		$err1066 = 0;
                if ($answer==0) {
			$errors = 'теперь всё ок!';
                        #$prompt_errors->Exit;
                }
                $answer= $err1067;  #1024+43
		#print "1067=$answer\n";
                for (my $i=1; $i<256; $i=$i*2) {
                        if (($answer&$i)!=0) {
				$timestamp = &timestamp;
				$errnum = ($answer&$i);
                                $errors_JobM = "$EnErrJobM{$errnum}";
				#my $dbh = DBI->connect("dbi:SQLite:dbname=$dbfile","","");
                                #$dbh->do("INSERT INTO maperr
				#	(date, errtype, errnum, errhuman) VALUES (?,?,?,?)", undef, "$timestamp", '1067', "$errnum", "$errors_JobM"
                                #);
                                # $dbh->disconnect;
                        }
                }
		$err1067 =0;
                if ($answer==0) {
                        $errors_JobM = 'теперь всё ок!';
                        #$prompt_errors_JobM->Exit;
                }		
                $answer= $err1068;  #1024+44 (AddrMem+_St_RSWarning);
                for (my $i=1; $i<256; $i=$i*2) {
                        if (($answer&$i)!=0) {
				$timestamp = &timestamp;
				$errnum = ($answer&$i);
                                $errors_ErrJob = "$EnErrJob{$errnum}";
				#my $dbh = DBI->connect("dbi:SQLite:dbname=$dbfile","","");
                                #$dbh->do("INSERT INTO maperr 
                                #(date, errtype, errnum, errhuman)
                                #        VALUES (?,?,?,?)", undef,
                                #        "$timestamp", '1068', "$errnum", "$errors_ErrJob"
                                #);
                                # $dbh->disconnect;
                        }
                }
		$err1068 = 0;
                if ($answer==0) {
                        $errors_ErrJob = 'теперь всё ок!';
                        #$prompt_errors_ErrJob->Exit;
                }

	}#end of power and errors	
	#if ($settings){
		
		$read_counter++;
		my ($map_version, $map_VerPlatPow, $map_chip_num,$map_versions_power_num, $map_dev_vers);
		#unless ($read_counter > 1){ #no need to read more than once
			@mapcommand =('P', 'C', 'P', 'R', '4', '0', '0', '6', 'C', "\r", "\n");
			($map_version, $map_VerPlatPow, $map_chip_num,$bs,$bs,$map_versions_power_num, $map_dev_vers,
                        $bs, $bs, $bs, $bs, $bs, $bs, $bs, $bs, $bs, $bs ) = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
			($map_version, $map_VerPlatPow, $map_chip_num,$bs,$bs,$map_versions_power_num, $map_dev_vers,
			$bs, $bs, $bs, $bs, $bs, $bs, $bs, $bs, $bs, $bs ) = readmappage('0') unless ($port_not_opening); #read a page of 16 bytes after address=0 
			my %device_vers = ( '0' => '','1'=> 'МАП', '2' => 'МАП LCD', '3' =>'SIN');
			%device_vers = ( '0' => '','1'=> 'MAC', '2' => 'MAC LCD', '3' =>'SIN') if ($lang eq 'en_US.UTF-8');
			my $map_version_type = $device_vers{$map_version};
			%device_vers = ( '0' => '1','1'=>'1.5','2'=>'2','3'=>'3',4=>'4.5',5=>'6',6=>'9',7=>'12');
			my $map_power_num = $device_vers{$map_versions_power_num};
			my $map_versions_power = $map_power_num.'кВт';
			$map_versions_power = $map_power_num.'kWt' if ($lang eq 'en_US.UTF-8');
			$map_power = $device_vers{$map_version};
                	%device_vers = ( '0' => '12','1'=>'24','2'=>'48');
			my %device_qty = ( '0' => '1','1'=>'2','2'=>'4');
                	my $map_versions_uacc = $device_vers{$map_dev_vers};	
			$qty = $device_qty{$map_dev_vers};
			my $temporarty = $map_chip_num;
			my $real = $temporarty>>5;
			my $int = $map_chip_num&0x1F;

			
			#if (($real < 8) && ($int <5)){ #will not work w/this version!
			#	$errors_version = 'Обновите прошивку МАП!'. " (ваша версия $real\.$int)";
			#	$prompt_errors_version = $mw->Dialog(-title => 'Ошибки:', -textvariable => \$errors_version, -bitmap => 'warning', -font=>'bar_rus');	
			#	$prompt_errors_version->after( 3000, sub {$prompt_errors_version->Exit });
			#	$prompt_errors_version->Show();				
			#}
			my $map_version_chip = ' ПО: '.$int.'.'.$real;
			$map_version_chip = ' Rel: '.$int.'.'.$real if ($lang eq 'en_US.UTF-8');
			$map_versions = $map_versions_uacc.'В/'.$map_versions_power.' Тип: '.$map_version_type.' Плата: '.$map_VerPlatPow.'.0'.' '.$map_version_chip;
			$map_versions = $map_versions_uacc.'Vdc/'.$map_versions_power.' Type: '.$map_version_type.' Chipset: '.$map_VerPlatPow.'.0'.' '.$map_version_chip if ($lang eq 'en_US.UTF-8');;
			$map_power = $map_power_num+0.5;
			$map_current_max = ($map_power_num*1000/(($qty*$map_versions_uacc)))+($map_power_num*1000/(($qty*$map_versions_uacc))*0.3); #1000/12; +333
			$c->itemconfigure($map_versions_text,-text => $map_versions);
			@mapcommand =('P', 'C', 'R', 'D', '4', '0', '0', '6', 'C', "\r", "\n"); #back to default
		#}           
	if ($settings){

				
		@mapcommand =('P', 'C', 'P', 'R', '4', '0', '0', '6', 'C', "\r", "\n");
		($signal_form, $bs, $map_voltage_generated, $bs, $bs, $map_voltage_acc_gen_end, $load_start,
                $bs, $bs, $bs, $bs, $bs, $bs, $bs, $bs, $bs) = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
		($signal_form, $bs, $map_voltage_generated, $bs, $bs, $map_voltage_acc_gen_end, $load_start,
		$bs, $bs, $bs, $bs, $bs, $bs, $bs, $bs, $bs) = readmappage('312') unless ($port_not_opening);
		
		$map_voltage_generated = 100 + $map_voltage_generated;
		$map_voltage_acc_gen_end = sprintf("%.1f", (($map_voltage_acc_gen_end/10)*$qty));
		$load_start = sprintf("%02d", $load_start);
	
		($net_type_label, $map_net_level_upper, $map_net_level_lower, $net_control_alg, $map_min_extra_gen_level, $times, $times2,
                        $bs, $bs, $bs, $bs, $bs, $bs, $bs, $bs, $bs ) =	(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
		($net_type_label, $map_net_level_upper, $map_net_level_lower, $net_control_alg, $map_min_extra_gen_level, $times, $times2, 
			$bs, $bs, $bs, $bs, $bs, $bs, $bs, $bs, $bs )= readmappage('360') unless ($port_not_opening); #
		$net_type_label = ($net_type_label/10);
		$map_net_level_upper = 100 + $map_net_level_upper;
		$map_net_level_lower = 100 + $map_net_level_lower;
		$map_min_extra_gen_level = sprintf("%.1f", (($map_min_extra_gen_level/10)*$qty));
	
		($acc_consrv, $lcd_backlight, $sound_control, $bs, $conn_speed, $times_map, $map_max_charge_time, 
			$bs, $bs, $bs, $bs, $bs, $bs, $bs, $bs, $bs) = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
		($acc_consrv, $lcd_backlight, $sound_control, $bs, $conn_speed, $times_map, $map_max_charge_time, 
			$bs, $bs, $bs, $bs, $bs, $bs, $bs, $bs, $bs) = readmappage('433') unless ($port_not_opening);		
		$map_max_charge_time = sprintf("%01d", (($map_max_charge_time)*16/60));

		@mapcommand =('P', 'C', 'R', 'D', '4', '0', '0', '6', 'C', "\r", "\n"); #back to default
		unless ($port_not_opening) { 						#0x1b6 = 438 map time
			#my $times_map = &readmap('438');
			$time_hours_map = $times_map>>3;
			$time_hours_map = sprintf("%02d", $time_hours_map);
			$time_minutes_map = $times_map&0x7;
			$time_minutes_map *= 10;
			$time_minutes_map = sprintf("%02d", $time_minutes_map);
			if ($lang eq 'en_US.UTF-8'){
				$real_time_label = 'Set internal clock '.$time_hours_map.':'.$time_minutes_map.' ';
			} else {
				$real_time_label = 'Установка времени '.$time_hours_map.':'.$time_minutes_map.' ';
			}
			#$times = &readmap('365'); #0x16d = 365
			$time_savings_begin_hours = $times>>3;
                        $time_savings_begin_hours = sprintf("%02d", $time_savings_begin_hours);
                        $time_savings_begin_minutes = $times&0x7;
                        $time_savings_begin_minutes *= 10;
                        $time_savings_begin_minutes = sprintf("%02d", $time_savings_begin_minutes);
			if ($lang eq 'en_US.UTF-8'){
				$time_savings_begin_label = 'Low Cost Savings / Time Settings Begin ('.$time_savings_begin_hours.':'.$time_savings_begin_minutes.')';
			} else {
                        	$time_savings_begin_label = 'Мин Тариф Начало ('.$time_savings_begin_hours.':'.$time_savings_begin_minutes.')';
			}
			#$times2 = &readmap('366'); #0x16e = 366
                        $time_savings_end_hours = $times2>>3;
                        $time_savings_end_hours = sprintf("%02d", $time_savings_end_hours);
                        $time_savings_end_minutes = $times2&0x7;
                        $time_savings_end_minutes *= 10;
                        $time_savings_end_minutes = sprintf("%02d", $time_savings_end_minutes);
			if ($lang eq 'en_US.UTF-8'){
				$time_savings_end_label = 'Low Cost Savings / Time Settings End ('.$time_savings_end_hours.':'.$time_savings_end_minutes.')';
			} else {
				$time_savings_end_label = 'Мин Тариф Конец ('.$time_savings_end_hours.':'.$time_savings_end_minutes.')';
			}
		}
		my $dbfile = $homedir.'/sqlite.db';
        	my $filesize;
        	$os = $^O;
        	if ($os =~ /Win/i){
                	$databasepath = $homedir.'\sqlite.db';
                	$filesize = format_bytes(-s $databasepath); # 4.5M
                	$homedirtext = 'База данных: '.$homedir.'\sqlite.db'. " (Размер: $filesize)";
        	} else {
                	$databasepath = $homedir.'/sqlite.db';
                	$filesize = format_bytes(-s $databasepath); # 4.5M
                	$homedirtext = 'База данных: '.$dbfile. " (Размер: $filesize)";
	        }
		
		$read_counter = 10 if ($read_counter > 1000);
	}
	#print "logcount = $logcount\n";
	#&logme(%log) if (($logcount == 2) && (!$port_not_opening)); #process only second entries
	
	if ($log{$logcount}{'v_acc'} > 0){
		my $dbh = DBI->connect("dbi:SQLite:dbname=$dbfile","","");
		$dbh->do("INSERT INTO maplog 
			(count, date, status_map, status_acc, v_acc, v_in, v_out, power, current_acc, current_net, freq, t_acc, t_tor, t_trans)
                	VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)", undef,
                        "$log{$logcount}{'count'}","$log{$logcount}{'date'}","$log{$logcount}{'status_map'}","$log{$logcount}{'status_acc'}","$log{$logcount}{'v_acc'}",
                        "$log{$logcount}{'v_in'}","$log{$logcount}{'v_out'}","$log{$logcount}{'power'}","$log{$logcount}{'current_acc'}","$log{$logcount}{'current_net'}",
			"$log{$logcount}{'freq'}","$log{$logcount}{'t_acc'}","$log{$logcount}{'t_tor'}","$log{$logcount}{'t_trans'}"
                );
        	$dbh->disconnect;
	}
	#&connect if ($port_not_opening);
	if ($port_not_opening){
		if ($conn_try_count > 2) { #manual connect
			&connect;
		} else {
			open_uart($port_not_opening);
			$conn_try_count=0;
		}
	}


}

sub timestamp {
	my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
	$year += 1900;
	$sec = sprintf("%02d", $sec);
	$min = sprintf("%02d", $min);
	$hour = sprintf("%02d", $hour);
	$mday = sprintf("%02d", $mday);
	$mon = sprintf("%02d", ($mon+1)); #don't know why
	my $sqlite_date = "$year-$mon-$mday $hour:$min:$sec"; 
	return($sqlite_date);
}

sub digit2ascii {
        my $digit=shift;
        if ($digit<10) {
                $digit=$digit+0x30; #print "digit2ascii digit = $digit\n";
        } else {
                $digit=$digit+0x41-10;
        }
        return $digit;
}

sub ascii2digit {
        my $ascii=shift;
        return 0x255 if ($ascii<0x30);
        if ($ascii>=0x41) {
                $ascii=$ascii-0x41+10;
        } else {
                $ascii-=0x30;
        }
        return 255 if ($ascii>15);
        return $ascii;
}
sub readmap { # READ from MAP 

        my $addr= shift;
        my ($error, $answer, $checksum);
        my ($a0, $a1, $a2, $s0, $s1);
        my $data;
	@mapcommand =('P', 'C', 'R', 'D', '4', '0', '0', '6', 'C', "\r", "\n");
	return if ($port_not_opening); #print "Read Map recieved $addr\n" if ($debug);

	my $temp = $addr>>8;
        $a0=&digit2ascii($temp);
	$temp = ($addr>>4)&0x0F;
        $a1=&digit2ascii($temp);
	$temp = $addr&0x0F;
        $a2=&digit2ascii($temp);

        $mapcommand[4]=chr($a0);
        $mapcommand[5]=chr($a1);
        $mapcommand[6]=chr($a2);

        $checksum=(255-($a0+$a1+$a2)+1)&0xff;

	$temp = ($checksum>>4)&0x0F;
        $s0=&digit2ascii($temp);
	$temp = $checksum&0x0F;
        $s1=&digit2ascii($temp);

        $mapcommand[7]=chr($s0);
        $mapcommand[8]=chr($s1);
	#my $text = "$mapcommand[0]$mapcommand[1]$mapcommand[2]$mapcommand[3]$mapcommand[4]$mapcommand[5]$mapcommand[6]$mapcommand[7]$mapcommand[8](rn)";
	#print "mapcommand: addr=$addr command=$text";
        $answer="";

        my $result = send_mapcommand_to_device(@mapcommand); #send mapcommand byte by byte, wait for echo ... 

        if ($result != 0) {
	$error=2; #die ("Ошибка чтения последовательного порта $error");
                #$port_not_opening = $port_in_use;
                return 0xff;
	}
        
        ($result, $answer) = wait_device_response();
        if ($result != 0){
		$error=3;
		#$port_not_opening = $port_in_use; #die ("Ошибка чтения последовательного порта $error");
	}
	chop ($answer);
        chop ($answer); #print " [DESCISION: $answer] " if ($debug);

        if ($answer=~/MOk/ ) {

		$temp = (ord(substr($answer,3,1)));
                $a0=&ascii2digit($temp);
		$temp = (ord(substr($answer,4,1)));
                $a1=&ascii2digit($temp);
                $data=($a0<<4)+$a1;
                $error=0;
                return $data;
        } else {
                $error=1; #die ("Ошибка чтения последовательного порта $error");
                #$port_not_opening = $port_in_use;
        }
} # end ReadMap

sub readmappage { # READ from MAP 
        my $addr= shift;
        my ($error, $answer, $checksum, $a0, $a1, $a2, $data);
        $a0=digit2ascii($addr>>8);
        $a1=digit2ascii(($addr>>4)&0x0F);
        $a2=digit2ascii($addr&0x0F);
        $mapcommand[4]=chr($a0); $mapcommand[5]=chr($a1); $mapcommand[6]=chr($a2);
        $checksum=(255-($a0+$a1+$a2)+1)&0xff;
        $a0=digit2ascii(($checksum>>4)&0x0F); $a1=digit2ascii($checksum&0x0F);
        $mapcommand[7]=chr($a0); $mapcommand[8]=chr($a1);
        $answer='';
        my $result = send_mapcommand_to_device(@mapcommand); #send mapcommand byte by byte, wait for echo ... 
        if ($result != 0) {
                $error=2;
                #die ("Ошибка чтения последовательного порта $error");
                $port_not_opening = $port_in_use;
        }
        ($result, $answer) = wait_device_response();
        if ($result != 0){
                $error=3;
		#$port_not_opening = $port_in_use;
                die ("Ошибка чтения последовательного порта $error");
        }
        chop ($answer);
        chop ($answer);
        my $stringlength = length($answer) - 2;
        if ($answer=~/MOk/ ) {
                my $cnt=0; my $memnum=0;
                my @values=();
                my $string = '';
                my $b = 0;
                for (my $i=3; $i<$stringlength; $i=$i+2){
                        $a0=0; $a1=0; $data=0;
                        $b = $i+1;
                        $a0=ascii2digit(ord(substr($answer,$i,1))); #1
                        $a1=ascii2digit(ord(substr($answer,$b,1)));
                        $data=($a0<<4)+$a1;
                        push(@values, $data);
                }
                $error=0;
                return @values;
        } else {
                $error=1;
		#$port_not_opening = $port_in_use;
                #die ("Ошибка чтения последовательного порта $error");
        }
} # end ReadMapPage


sub prepare_eeprom { # write command to MAP 
	@mapcommand =('P', 'C', 'W', 'R', "\r", "\n"); # 0    1    2    3    4    5    6    7    8    9    10    11    12 
        my ($addr, $command) = @_;
        $addr = '0';
        $command = 3; #ComMAP_EEPromWR=3,//Необходимо установить эту команду, и следом произвести запись в EEProm, после этого флаг записи сбросится
        my ($error, $answer, $checksum, $data);
        my ($a0, $a1, $a2);
        my ($s0, $s1);
        my ($d0, $d1);
	my $temp;
        return if ($port_not_opening); #print "Read Map recieved $addr\n" if ($debug); 

	$temp = $addr>>8;
        $a0=&digit2ascii($temp);
	$temp = ($addr>>4)&0x0F;
        $a1=&digit2ascii($temp);
	$temp = $addr&0x0F;
        $a2=&digit2ascii($temp); 

        $mapcommand[4]=chr($a0);
        $mapcommand[5]=chr($a1);
        $mapcommand[6]=chr($a2); #print "a0=$a0 a1=$a1 a2=$a2 command=$command ";

	$temp = $command>>4;
        $d0 = &digit2ascii($temp);
	$temp = $command&0x0F;
        $d1 = &digit2ascii($temp);

        my $sum = 0; $sum = $a0+$a1+$a2+$command; $sum =0xff-$sum; $sum++;
	$temp = $sum>>4;
        $s0=&digit2ascii($temp);
	$temp = $sum&0x0F;
        $s1=&digit2ascii($temp); #print "d0=$d0 d1=$d1 s0=$s0 s1=$s1\n";

        $mapcommand[7]=chr($d0);
        $mapcommand[8]=chr($d1);
        $mapcommand[9]=chr($s0);
        $mapcommand[10]=chr($s1);
        $mapcommand[11]="\r";
        $mapcommand[12]="\n";

        $answer="";

        my $result = send_mapcommand_to_device(@mapcommand); #send mapcommand byte by byte, wait for echo ... 

        if ($result != 0) {
        $error=2; #die ("Ошибка чтения последовательного порта $error");
                $port_not_opening = $port_in_use;
                return 0xff;
        }

        ($result, $answer) = &wait_device_response;
        if ($result != 0){
                $error=3;
                $port_not_opening = $port_in_use; #die ("Ошибка чтения последовательного порта $error");
        }
        chop ($answer);
        chop ($answer); #print " [DESCISION: $answer]\n";

        if ($answer=~/MOk/ ) {
		
		$temp = ord(substr($answer,3,1));
                $a0=&ascii2digit($temp);
		$temp = ord(substr($answer,3,1));
                $a1=&ascii2digit($temp);
                $data=($a0<<4)+$a1;
                $error=0;
                return $data;
        } else {
                $error=1; #die ("Ошибка чтения последовательного порта $error");
                $port_not_opening = $port_in_use;
        }

} # end prepare_eeprom

sub writemap { # write command to MAP 

	&prepare_eeprom;

	@mapcommand =('P', 'C', 'W', 'R', '0', '0', '0', "\r", "\n"); # 0    1    2    3    4    5    6    7    8    9    10    11    12 
        my ($addr, $command) = @_;
        my ($error, $answer, $checksum, $data);
        my ($a0, $a1, $a2);
	my ($s0, $s1);
	my ($d0, $d1, $d2);
	my $temp;
        return if ($port_not_opening); #print "Read Map recieved $addr\n" if ($debug);

	$temp = $addr>>8;
        $a0=&digit2ascii($temp);
	$temp = ($addr>>4)&0x0F;
        $a1=&digit2ascii($temp);
	$temp = $addr&0x0F;
        $a2=&digit2ascii($temp);

        $mapcommand[4]=chr($a0);
        $mapcommand[5]=chr($a1);
        $mapcommand[6]=chr($a2); #print "a0=$a0 a1=$a1 a2=$a2 command=$command ";

	$temp = $command>>4;
	$d0 = &digit2ascii($temp);
	$temp = $command&0x0F;
	$d1 = &digit2ascii($temp); #was4 print "after &0x0f command = $command\n";


	my $sum = 0; $sum = $a0+$a1+$a2+$command; #print "sum of $a0+$a1+$a2+$command=$sum\n"; print "sum of 255 - $sum=";
	$sum = 255 - $sum; #print "$sum\n";	print "sum of $sum+1=";
	$sum = $sum + 1; #print "$sum\n"; #$sum = $sum *(-1) if ($sum <0); #print "pre sum=$sum\n"; #$checksum=(255-($a0+$a1+$a2)+1)&0xff;
	my $shifted = ($sum>>4)&0x0f; #was my $shifted = ($sum>>4); print "shifted = $shifted\n";
        $s0=&digit2ascii($shifted); #print "after >> s0=$s0\n";
	$shifted = $sum & 0x0F; #print "shifted now = $shifted\n";
        $s1=&digit2ascii($shifted); #print "a0=$a0 a1=$a1 a2=$a2 d0=$d0 d1=$d1 s0=$s0 s1=$s1 command=$command\n";
	
	$mapcommand[7]=chr($d0);
	$mapcommand[8]=chr($d1);
	$mapcommand[9]=chr($s0);
	$mapcommand[10]=chr($s1);
	$mapcommand[11]="\r";
	$mapcommand[12]="\n";

        $answer="";

        my $result = send_mapcommand_to_device(@mapcommand); #send mapcommand byte by byte, wait for echo ... 

        if ($result != 0) {
        $error=2; #die ("Ошибка чтения последовательного порта $error");
                $port_not_opening = $port_in_use;
                return 0xff;
        }

        ($result, $answer) = &wait_device_response;
        if ($result != 0){
                $error=3;
                #$port_not_opening = $port_in_use; #die ("Ошибка чтения последовательного порта $error");
        }
        chop ($answer);
        chop ($answer); #print " [DESCISION: $answer]\n";

        if ($answer=~/MOk/ ) {
		$temp = ord(substr($answer,3,1));
                $a0=&ascii2digit($temp);
		$temp = ord(substr($answer,3,1));
                $a1=&ascii2digit($temp); #was ($answer,4,1)
                $data=($a0<<4)+$a1;
                $error=0;
                return $data;
        } else {
                $error=1; #die ("Ошибка чтения последовательного порта $error");
                $port_not_opening = $port_in_use;
        }
} # end ReadMap

sub send_mapcommand_to_device { 
	my @mapcommand = @_;
	my $length = @mapcommand;
        #print "sending mapcommand to device: ", @mapcommand, "\n" if ($debug);
        my ($count_in, $string_in);
        my $ccnt = 0;
        for (my $i=0; $i< $length; $i++) {
                my $tosend = $mapcommand[$i];
		if (!defined($PortObj)){
	                        print "sudden disconnect at send_mapcommand_to_device first! port_in_use=$port_in_use\n";
				#$port_not_opening = 'ALL';
				$port_not_opening = $port_in_use;
                                &connect;
                                last;
                }
                my $sent = $PortObj->write($tosend);
           	while(1){ #receive echo
                        $ccnt++;
                        ($count_in, $string_in) = $PortObj->read(1);    #read 1 byte
                        if (!defined($string_in)){
				print "sudden disconnect second ! port_in_use=$port_in_use\n";
				$port_not_opening = $port_in_use;
				&connect;
				last;
			}
			last if ($ccnt > 250);
			next if ($string_in eq 'M');
			if ($count_in){
				return (-1) if ($count_in !=1); #error - can;t receive the byte
			}
                        last if ($string_in eq $tosend); #check if same char received, else continue while
                }
        }
        return 0; #no error
} # end send_mapcommand_to_device

sub wait_device_response {
        my $answer = "";
	my $ccnt = 0;
        while(1) {
		$ccnt++;
                my ($count_in, $string_in) = $PortObj->read(1); #read 1 byte
               	unless (defined($string_in)){
                                print "sudden disconnect second ! port_in_use=$port_in_use\n";
                                $port_not_opening = $port_in_use;
                                &connect;
                                last;
                }
		 if ($count_in != 1) { #err , return anyway the string too
                        return (-1, $answer);
                }
		last if ($ccnt > 250);
                $PortObj->write($string_in); #echo it
                $answer .= $string_in;
                return (0, $answer) if ($string_in eq "\n"); #exit ok, received string in answer
        }
}



sub shutdown {
	$count_shutdown++;
	#print "count_shutdown = $count_shutdown\n";

	if ($os =~ /Win/i){
		eval { require Win32;
			my $sMessage = "System Shutdown!\n";
			my $uTimeoutSecs = 45;
			my $bForce = 1;
			my $bReboot = "";
			if ($count_shutdown <= 1){
				Win32::InitiateSystemShutdown( "", $sMessage, $uTimeoutSecs, $bForce, $bReboot );
			}
		};
	} else { #linux
		system ('shutdown -t 5');		

	}
}
sub shutdownabort {
        $count_shutdown = 0;
        #print "count_shutdown = $count_shutdown\n";

        if ($os =~ /Win/i){
                eval { require Win32; Win32::AbortSystemShutdown("");};
	}
}



sub connect{
	#my $PortObj;
	my $Registry;
	my %RegHash;
	my (@keys, @values);
	#my $os = $^O;
	my (@ports);
	#my $buttonchoice;

	for (my $i=0; $i <= 20000; $i ++){ #start waiting for serial port to appear!
	#my @ok_ports = ('Exit');
	my @ok_ports = ();
	if ($os =~ /Win/i){
		eval {   require Win32;
                        require Win32::TieRegistry;
                        Win32::TieRegistry->import(TiedHash=>\%RegHash);
                        require Win32::SerialPort;
                        my $computer; my  $Registry= \%RegHash;
                        my @keys = keys( %{ $Registry->{"HKEY_LOCAL_MACHINE\\HARDWARE\\DEVICEMAP\\SERIALCOMM"} } );
                        my @values = values( %{ $Registry->{"HKEY_LOCAL_MACHINE\\HARDWARE\\DEVICEMAP\\SERIALCOMM"} } );
                        for (my $i=0; $i<@keys; $i++){
                                my $port_name = $keys[$i]; $port_name =~ s/\\//g; $port_name =~ s/\.//g;
                                next if ($port_name =~ /SmSrl/g); my $port = $values[$i];
                                eval {
                                        if ($PortObj = new Win32::SerialPort($port, 1)) { $PortObj->close; push(@ok_ports, $port);
                                	} else {
                                        	#print "$port not opening!\n"; 
					}
				}; 
			sleep (1);
                }};
	} else {
        	eval "use Device::SerialPort; 1" or die $@;
        	my $directory = '/dev';
        	opendir (DIR, $directory) or die $!;
        	while (my $file = readdir(DIR)) {
                	#print "$file\n";
                	push (@ports, "$directory/$file") if ($file =~ /ttyS/g);
                	push (@ports, "$directory/$file") if ($file =~ /ttyUSB/g);
        	}
        	closedir(DIR);
        	foreach my $port (@ports){
                	no warnings 'redefine';
                	local *Device::SerialPort::carp = sub {};
                	$PortObj = new Device::SerialPort($port, 1) or next;
                	$PortObj->close;
                	push(@ok_ports, $port);
                	sleep (1);
         	};
	}
	#ports ok is @ok_ports
	#foreach (@ok_ports){ print "these port options exist: $_\n";}

	$connbutt->destroy if (Exists($connbutt));
	
	#$connbutt = $mw-> Dialog(-title=>"Нет связи с МАП-ом:", -buttons => \@ok_ports, -bitmap => 'warning', -foreground=>'black', -background=>'red'); #->Show(); #print "conn=$connbutt\n";
	#my ($connbutt_text, $connbutt_text1, $connbutt_text2, $connbutt_text3);
	if ($lang eq 'en_US.UTF-8'){	
		$connbutt_text = 'Lack of communication w/mac:';
		$connbutt_text1 = 'Detecting COM ports:';
		$connbutt_text2 = 'while your COM port is being detected. If detected, please select it.';
		$connbutt_text3 = 'This dialog is updated every 5 seconds, please wait';

	} else {
		$connbutt_text = 'Нет связи с МАП-ом:';
		$connbutt_text1 = 'Программа ищет СОМ порты:';
		$connbutt_text2 = 'пока определится ваш порт и выберите его.';
		$connbutt_text3 = 'Окно обновляется каждые 5 секунд, подождите';
	}
	$connbutt = $mw-> Dialog(-title => $connbutt_text, -buttons => \@ok_ports, -bitmap => 'warning', -foreground=>'black',);
	$connbutt->Icon(-image => $ico);
	$connbutt->add("Label", -text => $connbutt_text1, -foreground=>'black', -font=>'bar_rus')->pack(-side=>'top');
	$connbutt->add("Label", -text => $connbutt_text2, -foreground=>'black', -font=>'bar_rus')->pack(-side=>'bottom');
	$connbutt->add("Label", -text => $connbutt_text3, -foreground=>'black', -font=>'bar_rus')->pack(-side=>'bottom');	

	if ($connbutt){
		$buttonchoice = $connbutt->bell;
		$buttonchoice = $connbutt->Show();
	}

	if ($buttonchoice eq 'Exit'){
		exit;
	} elsif ($buttonchoice) {
		open_uart($buttonchoice);
		$connbutt->destroy if (Exists($connbutt));
		return;

	} else { #people press the X signg
		if ($buttonchoice eq 'Exit'){
			if ($lang eq 'en_US.UTF-8'){
				$connbutt2 = $mw->Dialog(-title => 'Unable to launch program!', -text => 'Exit', -bitmap => 'warning', -font=>'bar_rus' )->Show();	
			} else {
				$connbutt2 = $mw->Dialog(-title => 'Запуск Невозможен!', -text => 'Завершить!', -bitmap => 'warning', -font=>'bar_rus' )->Show();
			}
			exit if ($map_operation == 33);#really disconnect
		}
		$connbutt->destroy if (Exists($connbutt));
		return;	
	}
	

	sleep(3);
	#$connbutt->forget;
	#$buttonchoice->forget;
	#$buttonchoice->destroy;
	$connbutt->destroy if (Exists($connbutt));
	#$buttonchoice->destroy;
	} #bye bye
	exit; #port didn't appear, exit the program for good

}
sub disconnect{
        unless ($port_not_opening){
                if ($PortObj){
                        $PortObj->close || warn "close failed";
                }
        }
}


sub open_uart {

	$port_in_use = shift;
	#print "will try $port_in_use\n";
        $port_not_opening ="";
        if ($os =~ /Win/i){ #win32
                eval {
                        $PortObj = new Win32::SerialPort ($port_in_use) or $port_not_opening = $port_in_use;
                };
        } else { #linux
                eval {
                        if ($PortObj = new Device::SerialPort ("$port_in_use")){
				#print "opening $port_in_use just fine\n";
			} else {
				#print "port $port_in_use not opening!\n";
				$port_not_opening = $port_in_use;
			}
                };
        }
	#print "Port not opening is $port_not_opening\n";
	return if ($port_not_opening);
        $PortObj->is_rs232;
        $PortObj->handshake("none");
	$PortObj->user_msg(1);
	#$PortObj->baudrate($conn_speed);
	$conn_speed = 19200 unless (defined $conn_speed);
	$conn_speed = 19200 if ($conn_speed < 9600);
	#$conn_speed = 19200;
	#print "conn_speed=$conn_speed\n";
	&connect unless ($PortObj->baudrate($conn_speed));
	#$PortObj->baudrate($conn_speed);
	#&connect;

        $PortObj->parity("none");
        $PortObj->databits(8);
        $PortObj->stopbits(1);
        $PortObj->read_const_time(100);       # 100 milliseconds 
        $PortObj->read_char_time(5);       #was 5   # avg time between read char
	$PortObj->buffers(4096, 4096);  # read, write
        $PortObj->parity_enable(1); 
	$PortObj->write_settings || undef $PortObj;
        #print "Can't change Device_Control_Block: $^E\n" unless ($PortObj);
}
































sub encoded_gif {

#END_OF_GIF
#return $gif;
#}

my $gif =  <<'END_OF_GIF';


[encoded data, 40204 characters]
N+gmD0zMfe7cdfvcTOtmDOij0T0zYYP0PndMZFiu+pZjYxgBAQA7
END_OF_GIF
return $gif;
}


sub encoded_but1 {

#END_OF_GIF
##return $gif;
##}
#
my $gif =  <<'END_OF_GIF';

[encoded data, 11324 characters]
v3ve594orQf+u4M/fOIX3/hmP35AAAA7
END_OF_GIF
return $gif;
}

sub encoded_but2 {

#END_OF_GIF
###return $gif;
###}
##
my $gif =  <<'END_OF_GIF';
[encoded data, 11472 characters]
END_OF_GIF
return $gif;
}

sub encoded_but_exit1 {

#END_OF_GIF
###return $gif;
###}
##
my $gif =  <<'END_OF_GIF';

[encoded data, 9120 characters]
gw8eUV6DAwIAOw==
END_OF_GIF
return $gif;
}

sub encoded_but_exit2 {
my $gif =  <<'END_OF_GIF';

[encoded data, 9196 characters]
AgA7
END_OF_GIF
return $gif;
}

sub encoded_gif_banner {

#END_OF_GIF
##return $gif;
##}
#
my $gif =  <<'END_OF_GIF';
[encoded data, 12768 characters]
QjXUQ0XURFXURWXURlXUgAAAOw==
END_OF_GIF
return $gif;
}
#

sub encoded_chartlogo1 {
my $gif =  <<'END_OF_GIF';
R0lGODlhLgBjAOf1AHcAAHYABEANZnUBXXkAZT0UZ6IAC0AXaqUEBXYJZUIcaJkBfr0AMLwANbwA
OpUQE74AQbQDQbIJDbwHE0wfepwIgZcUGqETGbQOFqsSEaYJh5UQfp4Og60VE7cTGFIofFUng5cU
gOoAUukAV1Eqd+0AT+kAXLIMj1cphcEUHrkXGsIVGLoZGloriKsTi1wtiqMiKMUZIFE0a9cOWqwh
IF0ui7MUlmEuhs4TVlgxi74eHcYcIa0jJ78gHvsJVlM5au4MYMgeImQxlu8OXMgfKGIzkPsLXFU7
bLYamb8XnvoNYcMkIWY3lLgem/oQZ/IUXfEUYmc4lbkfnPwTY2o6mLsinqAsjKcqj8Qgo2s8mm09
m6otkQ5ger8ooqs8PvkiYvgiaHVEoxZkftkzNBpmgLpEALhIALJKAABxm7A9m/owWvowYNsytHlQ
rQx0mdY3s5tSbVNxFwB8oFVyDu9AQlpxGRd4nfw9Xr1TVIpYufw/ZJ9bdJ5cel96DRSEqQCKtOpG
yNFjEwiPs7VeqACSu9ZmCgCUvdVbfyOLsA+RtZxoy99oEwCZwphszO9nAACbvupqAGuNItRoZ91k
jNVqbtFkviOZvXCSKPduAG6VFRSexyaav4iBpACmz/lwD3CXIxqgyfZzAPZzDh+iywep0iKjzYmI
q5WGoKOHdNByxdV4e/15BpGKop6LfPl8BXqgJP97C++AEf98DaKNeNp6kHyiJqaLnJaPp9d+kdN6
xdJ7zP+BDoGlINKBmNB9xv+CEv+GEpmXm4mjVn+rJSm03oyjZIqlX4OuKIitKYWvH5icq5meoI2o
YYWwKv+OGdeUVbiVqJefp4ayLTG54oSnsIm0L4apspOnpjO+4Ieqs6Skm6qjro24NJaqqZaptYqt
tsKig46tsJGtqpGstpSssJSrvMGjiZG7LYuvt5C7NpKxtI6yuvuhLbCtn+WlY/+kJ5m1spO3szfO
8JvFOIu8yI+8w/+rK53IQ9u4edq4f9a7gEna/KjRRbHhU7vrXb/uVyH+HkNyZWF0ZWQgd2l0aCBH
SU1QIGJ5IHBhc2hhbm9pZAAsAAAAAC4AYwAACP4AqQkcSLCgwYMIEypcyLChw4cQIzK0BYePxYsY
L+7hY02iwkMMGjRwAKGkyZMQIozzmBBXCREiRowwQbNmzRE4VrI82GvNkydQggodCmUIjm87D+LS
o6Sp06dOjSJNWnCpk6tYs2KVSrUqU6hPtx7tShDXHSNGlEwB82WK27dTnowlK7CXGh8+0n7Zy/et
3Kl0aeVFqxau4RmAyU4SAaSx48eOh8zQSXcbtMuYM2uGRrdzQWWsbokeHXq06VOmU6u+xTDNAAKw
Y8ueTbt27ASUEaY6UYGD79/Agy8Y3jt48A25D/p6o8GF8+fQo2uY3jx6dOQLdQFCYqO79+/gT/54
P4GEO3gbLrArzAWoS/n38OPLn18+fXKD7LFI2c+/v/8qAFbRX4BN1KdeQvkFqOCCDDaooH3ZAYJF
FxRWaOGFSWSYxIUUYuGhDQcipAsbVXho4okoYqFhEhN2kSIWVYRwX0GVJIFEEzjmqOOO8O24YxIc
zEjQIFdsYeSRRR6pZJJKNqmkFdks1JFBUR40pWdYUuWNDD8c4aWXP3T55ZhkHtFllRGVA0IBB7Tp
5gECxCnAm3QeUIACiT1UTh4ogIDCn4BSICgFfgJqaJ8k5OlQOYpk8UINkEYKwqQovHBDDpFm2kKi
HpXTSBtFhCrqqKSWuqmiDXnaRhRMtOrqq/6wuhrqqZ1+GsWtuOaqK66u0iqRqlRkIeywWdxKRbDE
ZnEsFS9w+msjYWShxbTURiGEEFFIS+22WhThbJp5IJvstUIwQcW0yQpLxbcQlVNDpS/EKy+gLchr
r70foMrQOJyY4u+/pvQL8MAEX5nlQ9lc083CDHcjzsPiXCOxw+I0bHHDEl/z8MUDwdNHHHOELPLI
JJds8hxxpGxyHVPFM08mMMcs88w012yzzJG07A8yr9Ti889ABy300ETX8krOAsXzzz28DOP001BH
LfXUVA9TC9LUKM1PM8c04/XXYIct9thhH2P21S3/ww831bTt9ttwxy133F+jnbQ/a3Oj9/7efPft
99+Ac8ML1krPw006iCeu+OKMN+54OscQ3s85lFdu+eWYZ6655ZdMBc85w5gt+uikl2766aIn80k4
AqkjDDOwxy67MbTTLvvtuNeOOzPFoHnwwdZ8I/zwxBdvPPEGP7QOGWKQ4fzzzXMh/fPUV6/vQvQ8
4oYd3HfPPRpobG+HHN577wY6HtEjTyKCIOL++4j8If8f8NePiBzoS0TPPp0QYsj/AAygAAUoCPyl
bx/EYMQmFshAQzDwgRDcRAHzF5H9TQMUmsigBhmhwQ5qkIETPOAFQUHCEmqihChEYQZDqD8EgmIU
MIyhDGc4w0QYsIWkGEUndsjDTsCwh/5ALEUpNnHDiNQDGy+k4Sg0CAofKnEUfqAgROjBvkRY8YpW
lB8iBIHFLiYiih75xjrGSMYymvGMZUze79ZIEG2gYhZwjKMc5dgKLD2jDGbIox73qMcynIF1ncFH
LCBByEIaspCOKAQg6aIPdojikZCMpCcmKYpALJIs+bDHKjbJyU5yspKX7EomYUHKUpqylKD0TCZ/
wcpWuhKVllSlPVxJS1emsjP6eEcrgcHLXvrSFbHsTD6cQcpf+PKYvFSkZ9yBiVCEIpLQfGQoFhFK
qrQDHObIpja3qU1ssrEr0ViGOMe5jGCEk5zLiEYw0MlOckaDIV4IAADmSU950vOe9vG8pz7xKaSB
UAIDBgioQAdKUAMgoKAINcAD+ikQVYwhAx2IqEQnSlEEUPSiErUAQ6mhCjqoAAMeCKlIRzpSCZD0
pCHtgEYX0tEgqIAFMI2pTGU6gZnOVAU4VelGO0oEHfj0p0AN6gSC6tMUpEAHMdUpS+nQ0x449alQ
heoEjJqCqDr1p0pVSEd3sIQdePWrYAXrCsaaAq529atBSCsGVqrVMaQgrXCNq1yDMNax7oAIRJhr
EFLA1oRIYgc6oKpgB0vYwBJWsBfYKB5owIPGOvaxkI2sZBtLAxhcTyDkyKxmMzuOzW62s54N7Wa/
SdrS/i4gADs=
END_OF_GIF
return $gif;
}
sub encoded_chartlogo2 {
my $gif =  <<'END_OF_GIF';
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
END_OF_GIF
return $gif;
}

sub encoded_ico {

#END_OF_GIF
##return $gif;
##}
#
my $ico =  <<'END_OF_ICO';
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
END_OF_ICO
return $ico;
}
sub encoded_but1eng {

my $gif =  <<'END_OF_GIF';
[encoded data, 11552 characters]
5Eu+gAAAOw==
END_OF_GIF
return $gif;
}
sub encoded_but2eng {
my $gif =  <<'END_OF_GIF';
[encoded data, 11628 characters]
J4TCKJTCKaTCKrQKwitswg45QpwJCAA7
END_OF_GIF
return $gif;
}
sub encoded_banner_eng {

my $gif =  <<'END_OF_GIF';
[encoded data, 10412 characters]
BW5whTtc4hbXuMdFbnKVu1zmNheyAQEAOw==
END_OF_GIF
return $gif;
}
sub encoded_but_exit1eng {
my $gif =  <<'END_OF_GIF';
[encoded data, 9044 characters]
FoAAiA21W2+/BTdcccclt1xyrcs2XdSAVbddd/eazt2AAAA7
END_OF_GIF
return $gif;
}
sub encoded_but_exit2eng {
my $gif =  <<'END_OF_GIF';
[encoded data, 9120 characters]
gw9GOGGFF2a4YYQJFliigAAAOw==
END_OF_GIF
return $gif;
}
